If verification is successful, NextJS redirect from login page to dashboard page
P粉021854777
P粉021854777 2023-08-13 10:56:17
0
1
674
<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>
P粉021854777
P粉021854777

reply all(1)
P粉986937457

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 desired route based on the validity of the session.

Here is a TS code that may help:

import { NextResponse } from 'next/server';
import { withAuth, NextRequestWithAuth } from 'next-auth/middleware';

export default withAuth(function middleware (request: NextRequestWithAuth) {
    const session = request?.nextauth?.token;

    if (request.nextUrl.pathname === '/') return NextResponse.next();
    if (!session && request.nextUrl.pathname !== '/login') 
        return NextResponse.redirect(new URL('/login', request.url));
    if (session && request.nextUrl.pathname !== '/dashboard')
        return NextResponse.redirect(new URL('/dashboard', request.url));

    return NextResponse.next();
},
{
    callbacks: {
        authorized: () => true,
    },
});

export const config = {
    matcher: [
        '/((?!api|_next/static|_next/image|favicon.ico).*)',
    ],
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template