DEV Community

Kb Bohara
Kb Bohara

Posted on

Nextjs and next auth middleware baby.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getToken } from 'next-auth/jwt';

export async function middleware(request: NextRequest) {
  const token = await getToken({ req: request, secret: process.env.NEXT_AUTH_SECRET });
  const { pathname } = request.nextUrl;

  // If the user is logged in and they try to access /signin , /, redirect them away.
  const unAuthorizedRouteOnly = ["/signin", "/"]
  if (token && unAuthorizedRouteOnly.includes(pathname)) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // If no token is found and they are not already on /signin or /, redirect to /signin.
  if (!token && !unAuthorizedRouteOnly.includes(pathname)) {
    const signInUrl = new URL('/signin', request.url);
    signInUrl.searchParams.set('callbackUrl', request.url);
    return NextResponse.redirect(signInUrl);
  }

  // Allow the request to proceed if none of the above conditions are met.
  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)