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
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server