NextJS redirect from login to dashboard if authenticated – Javascript

by
Ali Hasan
next.js reactjs

Quick Fix: Implement a middleware in the root directory of your project to check if the session has a valid JWT token. If it does and the user is trying to access the login or register page, redirect them to the dashboard. Otherwise, continue as normal.

The Solutions:

Solution 1: Middleware for Authentication and Redirection

To handle the redirection of authenticated users away from specific pages (like the login page) in Next.js, you can utilize a middleware function. Here’s a detailed explanation of how it works:

  1. Middleware Function:
    • Create a file named middleware.ts in the root directory of your Next.js project.
    • Import necessary modules like NextResponse and getToken from next-auth/jwt.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';
  1. middleware Function:
    • Define an async function called middleware that takes a NextRequest object as its argument.
export async function middleware(req: NextRequest) {
  1. Get JWT Token:
    • Use the getToken() function to extract the JSON Web Token (JWT) from the request. This function requires a secret key, which can be obtained from your Next.js authentication configuration.
const session = await getToken({ req, secret });
  1. Check URL Path:
    • Extract the pathname property from the request’s nextUrl object. This represents the current URL path that the user is trying to access.
const { pathname } = req.nextUrl;
  1. Redirect Authenticated Users:
    • Check if the session object exists (indicating a logged-in user) and if the current path is either /login or /register. If both conditions are met, redirect the user to the root URL (/).
if (session && (pathname === '/login' || pathname === '/register')) {
    return NextResponse.redirect(new URL('/', req.url));
}
  1. Allow Access for Non-Authenticated Users:
    • If the user is not authenticated or is trying to access a different page, simply allow the request to continue by returning NextResponse.next().
return NextResponse.next();
  1. config Object:
    • In a separate export statement, define a config object to specify the paths for which this middleware should run. You can provide a single string or an array of path matchers.
export const config = {
  matcher: ['/api/auth/:path*', '/'],
};
  1. Usage:
    • This middleware will automatically run for the specified paths and redirect authenticated users away from the login and register pages to the root URL.

Solution 2: Improved Implementation

In this implementation, we’ll utilize the `withAuth` middleware from `next-auth/middleware` to verify the user’s session and redirect them appropriately. Here’s the modified code:

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

export const middleware = withAuth(
  (req: NextRequestWithAuth) => {
    // Retrieve the session from the NextAuth context
    const session = req?.nextauth?.token;

    // Handle the redirect based on session validity and current URL
    if (req.nextUrl.pathname === '/') {
      return NextResponse.next();
    } else if (!session && req.nextUrl.pathname !== '/login') {
      return NextResponse.redirect(new URL('/login', req.url));
    } else if (session && req.nextUrl.pathname !== '/dashboard') {
      return NextResponse.redirect(new URL('/dashboard', req.url));
    }

    // Proceed to the next request if the conditions are met
    return NextResponse.next();
  },
  {
    callbacks: {
      authorized: () => true,
    },
  }
);

export const config = {
  matcher: [
    // Match all routes except API routes, static files, and certain paths
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

With this implementation, we ensure that authenticated users are redirected to the dashboard, while unauthenticated users are redirected to the login page when attempting to access non-public routes.

Q&A

How can I modify the given code so that if a user is authenticated and the page is something like the login, redirect them to the dashbosrd or something?

You can use withAuth middleware to validate the session and redirect to the desired route depending on the session validity.

Can I use matcher in the config to maintain the private URLs and prevent logged in users from accessing specific public ones?

No, matcher is primarily used to specify the paths for which the middleware function should run.

Video Explanation:

The following video, titled "Next.js 14 Authentication Tutorial (Super EASY!) - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... of ur app goes bust etc . Auth is something which is a pain but has to be done the right way. 40:27. Go to channel · Next-Auth Login ...