We created a NextJS Middleware to ensure that all pages inside app folder need an authentified user to be available.
Here is the code for our AppMiddleware:
apps/web/lib/middleware/app.ts
Copy
export async function AppMiddleware(req: NextRequest) { // get the current session from request cookies const session = (await getToken({ req, secret: process.env.NEXTAUTH_SECRET, })) as { email?: string; user?: { id: string; }; }; // if the session is undefined and the requested url is not public, then redirect to sign-in. if (!session?.email && !isPublic(req)) { return NextResponse.redirect( new URL( '/sign-in', req.url ) ) } const searchParams = req.nextUrl.searchParams.toString(); const searchParamsString = searchParams.length > 0 ? `?${searchParams}` : ""; const fullPath = `${req.nextUrl.pathname}${searchParamsString}`; return NextResponse.rewrite(new URL(`/app${fullPath}`, req.url))}function isPublic(req: NextRequest) { // <- if you need more public pages, change this function. return ['/sign-in'].includes(req.nextUrl.pathname)}