I am following this tutorial on Nextjs.org: It uses Response.redirect inside the authorized
callback:
import type { NextAuthConfig } from 'next-auth';
export const authConfig = {
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
if (isOnDashboard) {
if (isLoggedIn) return true;
return false; // Redirect unauthenticated users to login page
} else if (isLoggedIn) {
return Response.redirect(new URL('/dashboard', nextUrl));
}
return true;
},
},
providers: [], // Add providers with an empty array for now
} satisfies NextAuthConfig;
However, ChatGPT and Gemini both recommend not using redirect inside the authorized
callback – it should only be used to determine whether the user is authorized to access that page/route.
But, given that this is the official tutorial – is this a valid pattern or not?
This code is written inside /auth.config.ts
file as the tutorial says. and then this file is later imported inside /middleware.ts
. So that means this Response.redirect()
from callback is being called inside the middleware.
As nextjs API doc says about middleware is that:
Middleware executes before routes are rendered. It’s particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects.
So I think It might be a good place to write redirects.
But I don’t exactly know in what aspect they (ChatGPT and Gemini) are not recommending using redirects in callbacks.