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).*)'], };

Feb 23, 2025 - 15:14
 0
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).*)'],
};