How to implement a "return to previous page" after login in Next.js?
I'm using nextjs v15 with app router, and I need functionality like when a user clicks a login button from any page, they should be redirected back to that same page after successful login. It sounds common and easy. But I want to know how we can do that as Nextjs way without any extra tracking with session store or window object wiht listeners.
I did not get any method or help using useRouter and useParam hooks.
What I'm trying to achieve:
Sharing minimal code for context.
SignIn Page:
export default function Page() {
...
const callbackUrl = "/";
// temporarily using callback to '/'
// so always redirect to home after login
if(authenticated){
return router.back();
// it does not redirect properly.
// page reloads once unnceesarily then goes back
};
return (
<>
{
Object.values(providers).map((provider) => (
<LoginButton
callbackUrl={callbackUrl}
providerId={provider.id}
providerName={provider.name}
/>
))
}
</>
);
}
Actual Login Button to Invoke SignIn:
import { signIn } from 'next-auth/react';
const LoginButton = ({ callbackUrl, providerId, providerName }) => {
const handleSignin = () => {
signIn(providerId, {callbackUrl:callbackUrl}
}
return (
<ButtonContainer onClick={handleSignin} >
...
</ButtonContainer>
);
};
Sign in menu button on AppBar:
const UserMenu = () => {
...
if(!user){
return (
<Link href={'/auth/signin'}>
<Button>Sign in</Button>
</Link>
);
}
return (...)
};
If we get the previous url or callback url, then we cna it with signin method of NexAuth
which automatically redirects to there.
What I've considered:
But I'm looking for the easy, simple, straight way, like I am expecting built-in Next.js APIs or methods—the approach that works well with Next.js App Router.
Long story short:
I'd appreciate any code examples or best practices to implement this functionality.
Got solution from iTollu's comment
Passing param to Link href.
import { usePathname } from 'next/navigation';
const UserMenu = ({iniUser}) => {
const pathname = usePathname();
const href = `/auth/signin?callbackUrl=${encodeURIComponent(pathname)}`;
return (
<Link href={href}>
<Button>Sign in</Button>
</Link>
);
};
Extracting param in Sign in Page.jsx
import { signIn } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
export default function SigninPage(){
const router = useRouter();
const searchParams = useSearchParams();
const callbackUrl = searchParams.get('callbackUrl') || '/';
const signinWithCallback = () => signIn(providerId, {callbackUrl});
return(
...
)
}
Simple as that!