If verification is successful, NextJS redirect from login page to dashboard page
P粉021854777
2023-08-13 10:56:17
<p>With this example, I can have nextjs redirect to a specified page, such as the login page, if someone is not authenticated. However, how can I modify this so that if the user is authenticated and the page is something like a login page, redirect them to the dashboard or another page? Is there a configuration that can achieve this? Something like <code>matcher</code> will maintain private URLs nicely. But how do I fix this for a specific public URL that I don't want users to access while logged in? Is this possible? </p>
<pre class="brush:php;toolbar:false;">import { NextRequest, NextResponse } from 'next/server'
export async function middleware(req: NextRequest, res: NextResponse) {
const token = req.headers.get('token') // TODO: Get the token from the request header
const userIsAuthenticated = false // TODO: Check if user is authenticated
console.log('middleware.ts', 'token', token);
if (!userIsAuthenticated) {
const signinUrl = new URL('/login', req.url)
return NextResponse.redirect(signinUrl)
}
return NextResponse.next()
}
// Here you can specify all paths where this middleware function should run
// Supports a single string value or an array of matchers
export const config = {
matcher: ['/api/auth/:path*', '/'],
}</pre>
Assuming you are using Next-Auth for authentication:
Wrap the middleware using
withAuth
and authenticate the session using the token variable provided by Next-Auth, then redirect to your desiredroute
based on the validity of the session.Here is a TS code that may help: