user redirected to login page after a trying to access a protected page. I am storing the protected page url in search params and after login redirect to that page. (my approach works on localhost just fine but after hosting or vercel it always redirect to homepage)
I am using middleware to assign the url
//middleware.ts
const { pathname } = request.nextUrl;
if (!token && isLoginProtectedPath) {
const redirectUrl = pathname;
(await cookies()).set('redirect_url', redirectUrl);
return NextResponse.redirect(new URL('/auth/login', request.url));
}
//login page
const searchParams = useSearchParams();
startTransition(async () => {
const res = await login(payload);
if (res.success) {
setIsLogged(true);
console.log('login - redirectUrl', redirectUrl);
router.push(searchParams.get('redirect_url') || redirectUrl);
return;
}
toast.error(res.message);
});
Expecting not to go to homepage and go to searchparams assigned url
Answer
It's possible that environment variables are messing with the code, make sure to check them on Project Settings > Environment Variables