Skip to content

Instantly share code, notes, and snippets.

@smyaseen
Created June 18, 2024 08:35
Show Gist options
  • Save smyaseen/eb1ad52e85b7a6665642430bc4b9da31 to your computer and use it in GitHub Desktop.
Save smyaseen/eb1ad52e85b7a6665642430bc4b9da31 to your computer and use it in GitHub Desktop.
Validate user authentication on edge with NextAuth & NextJS Middleware
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
import { withAuth } from 'next-auth/middleware';
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
const pathsToExclude = /^(?!\/(api|_next\/static|favicon\.ico|manifest|icon|static|mergn)).*$/;
// set of public pages that needed to be excluded from middleware
const publicPagesSet = new Set<string>(['home']);
const rootRegex = /^\/($|\?.+|#.+)?$/;
export default async function middleware(req: NextRequest, event: NextFetchEvent) {
if (!pathsToExclude.test(req.nextUrl.pathname) || publicPagesSet.has(req.nextUrl.pathname))
return NextResponse.next();
const token = await getToken({ req });
const isAuthenticated = !!token;
// if user goes to root path '/' then redirect
// /dashboard if authenticated
// /login if unauthenticated
if (rootRegex.test(req.nextUrl.pathname)) {
if (isAuthenticated) return NextResponse.redirect(new URL('/dashboard', req.url)) as NextResponse;
return NextResponse.redirect(new URL('/login', req.url)) as NextResponse;
}
// redirects user from '/login' if authenticated
if (req.nextUrl.pathname.startsWith('/login') && isAuthenticated) {
return NextResponse.redirect(new URL('/dashboard', req.url)) as NextResponse;
}
// This has to be same page option as in AuthOptions
const authMiddleware = await withAuth({
pages: {
signIn: `/login`,
},
});
return authMiddleware(req, event);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment