#Protect route
1 messages · Page 1 of 1 (latest)
Yes, you can use Next.js middleware to restrict access to pages while unauthenticated. Middleware allows you to intercept requests and perform actions like authentication checks before rendering the page. This can help prevent the flash of unauthenticated content you're experiencing.
To implement this, you can create a middleware.ts file and export a middleware function that checks for authentication. If the user is not authenticated, you can return a NextResponse with a redirect to the /login page.
Here's an example from the extracts:
// middleware.ts
import { NextRequest, NextResponse } from 'next/server'
import { isAuthenticated } from '@lib/auth'
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/:function*',
}
export function middleware(request: NextRequest) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond with JSON indicating an error message
return new NextResponse(
JSON.stringify({ success: false, message: 'authentication failed' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
}
You can modify the matcher in the config object to target the specific pages you want to restrict access to. Also, update the isAuthenticated function to use your authentication logic.
For more information on using middleware, refer to the Next.js documentation (https://nextjs.org/docs/middleware).