skip to Main Content

we are currently developing an application with NextJS 13 using next-auth, so far everything is great. Our application uses a custom sign-in page with a CredentialsProvider and we protect our routes using the next-auth middleware. We would like to prevent our users from accessing /login if they are already authenticated. We managed to achieve this in the client with useSession() but we are looking for a way to have this logic in the middleware instead. Is this possible to achieve with the current next-auth middleware implementation? Below is our current middleware and route configurations. Thank you.

//middleware.ts
import withAuth from 'next-auth/middleware';

export default withAuth({
  pages: {
    signIn: `/login`,
  },
});

and

//route.ts
import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';

const handler = NextAuth({
  pages: {
    signIn: `/login`,
  },
  session: {
    strategy: 'jwt',
  },
  providers: [
    CredentialsProvider({
      name: 'Credentials',
      credentials: {
        username: { label: 'Username', type: 'text' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials, req) {
        //auth logic here
      },
    }),
  ],
});

export { handler as GET, handler as POST };

2

Answers


  1. Chosen as BEST ANSWER

    This is working for us. Also credits to @Yilmaz, this is based on his answer.

    import { getToken } from 'next-auth/jwt';
    import { withAuth } from 'next-auth/middleware';
    import { NextFetchEvent, NextRequest, NextResponse } from 'next/server';
    
    export default async function middleware(req: NextRequest, event: NextFetchEvent) {
      const token = await getToken({ req });
      const isAuthenticated = !!token;
    
      if (req.nextUrl.pathname.startsWith('/login') && isAuthenticated) {
        return NextResponse.redirect(new URL('/dashboard', req.url));
      }
    
      const authMiddleware = await withAuth({
        pages: {
          signIn: `/login`,
        },
      });
    
      // @ts-expect-error
      return authMiddleware(req, event);
    }
    

  2. import { getToken } from "next-auth/jwt";
    import { withAuth } from "next-auth/middleware";
    import { NextResponse } from "next/server";
    
    // For the time being, the withAuth middleware only supports "jwt" as session strategy.
    export default withAuth(
      async function middleware(req) {
        const token = await getToken({ req });
        // if token exists, !!token will be true
        const isAuthenticated = !!token;
       
        // first, check if the current path is login page
        if (req.nextUrl.pathname.startsWith("/login")) {
          // I am in "login" page now  I check if the user is authenticated or not
          if (isAuthenticated) {
             // If I get here it means user is on "login" page and it is authenticated. then redirect it to whatever url
            return NextResponse.redirect(new URL("/whatever", req.url));
          }
         
        }
    );
    
    // specify on which routes you want to run the middleware
    export const config = {
      matcher: ["/", "/login""],
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search