Protect certain route after auth ? NextAuth middleware

Hi is there any possible way to protect my pages after auth in middleware ? i dont want to do it in client side since it will flash the content for a second , and if i do it with unstable_getServerSession it feels kinda toomuch code duplication ? if i have auth i want to protect page A,B,C,D but if i dont have auth i want to protect page E,F,G,H this is currently how my code look like but is there any other way to do it way more cleverly ? Thanks
// middleware.ts
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';

const PROTECT_ROUTE_WITHOUT_AUTH = ['/private-route'];
const PROTECT_ROUTE_WITH_AUTH = ['/sign-in'];

export async function middleware(req) {
const noAuthRedirectUrl = req.nextUrl.clone();
noAuthRedirectUrl.pathname = '/sign-in';

const withAuthRedirectUrl = req.nextUrl.clone();
withAuthRedirectUrl.pathname = '/';

if (PROTECT_ROUTE_WITHOUT_AUTH.includes(req.nextUrl.pathname)) {
const session = await getToken({
req,
});
if (!session) return NextResponse.redirect(noAuthRedirectUrl);
}

if (PROTECT_ROUTE_WITH_AUTH.includes(req.nextUrl.pathname)) {
const session = await getToken({
req,
});
if (session) return NextResponse.redirect(withAuthRedirectUrl);
}

return NextResponse.next();
}
// middleware.ts
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';

const PROTECT_ROUTE_WITHOUT_AUTH = ['/private-route'];
const PROTECT_ROUTE_WITH_AUTH = ['/sign-in'];

export async function middleware(req) {
const noAuthRedirectUrl = req.nextUrl.clone();
noAuthRedirectUrl.pathname = '/sign-in';

const withAuthRedirectUrl = req.nextUrl.clone();
withAuthRedirectUrl.pathname = '/';

if (PROTECT_ROUTE_WITHOUT_AUTH.includes(req.nextUrl.pathname)) {
const session = await getToken({
req,
});
if (!session) return NextResponse.redirect(noAuthRedirectUrl);
}

if (PROTECT_ROUTE_WITH_AUTH.includes(req.nextUrl.pathname)) {
const session = await getToken({
req,
});
if (session) return NextResponse.redirect(withAuthRedirectUrl);
}

return NextResponse.next();
}
1 Reply
jix74
jix743y ago
This isn't the answer you're looking for but you COULD do client side and just use CSS transitions to remove flashing. Since you're using middleware, this means that you're not using T3's default database strategy right? You're just using JWT session strategy right?

Did you find this page helpful?