Next.js Discord

Discord Forum

Redirect when auth0 access token expires

Unanswered
Canaan Dog posted this in #help-forum
Open in Discord
Avatar
Canaan DogOP
I have been trying to logout user as per requirement when access token expires in next14 app with auth0. Along with that, I have integrated apollo client for server and client components separately to use graphql queries.
I have tried two ways:
1. To somehow redirect through interceptor (Graphql Client) when I get error there of forbidden resource or token expired etc.
2. To redirect from middleware by checking validity of token by decoding using jwt library. This somehow throws me into infinite renders and hence I see on browser too many renders error.
As I am using sdk so I am using default code for it.
// // app/api/auth/[auth0]/route.js
import { handleAuth } from '@auth0/nextjs-auth0';
export const GET = handleAuth();

Here is middleware code
export default async function middleware(req: NextRequest) {
const path = req.nextUrl.pathname;
const token = await getTokenFromSession();
if (
path.startsWith('/_next')
path.includes('/invitation')

path.includes('/error')
) {
return NextResponse.next();
}
if (path.startsWith('/api/auth/logout')) {
return NextResponse.next();
}

if (token && isTokenExpired(token)) {
console.log('LOGGIN OUT');
// Redirect to logout if the token is expired
const logoutRedirectUrl = ${req.nextUrl.protocol}//${req.nextUrl.host}/api/auth/logout;
return NextResponse.redirect(logoutRedirectUrl);
}

if (path === '/' && token) {
const httpsRedirectUrl = ${req.nextUrl.protocol}//${req.nextUrl.host}/leads;
return NextResponse.redirect(httpsRedirectUrl);
}

if (path.includes('/api/auth/login') && token) {
const httpsRedirectUrl = ${req.nextUrl.protocol}//${req.nextUrl.host}/leads;
return NextResponse.redirect(httpsRedirectUrl);
}

if (protectedRoutes.includes(path) && !token) {
const loginRedirectUrl = ${req.nextUrl.protocol}//${req.nextUrl.host}/api/auth/login;
return NextResponse.redirect(loginRedirectUrl);
}

return NextResponse.next();
}

0 Replies