After logged in, how to redirect users back to the same URL they were before logging in?

My app sells event tickets and I'm using NextAuth. Unauthenticated users can go as far as selecting an event and then selecting the tickets they want. Once the ticket is selected, the "continue" button leads the user to "/tickets/register". In that page I verifiy if the user is authenticated. If it's not, it is redirected to: "/api/auth/signin" But after logging in, users are being redirected back to "/", when I actually want them to be redirected back to the same page they were before ("/api/auth/signin"). I obviously don't want that URL to be the standard after every authentication. It should only happen in this registering flow. (As some users might decide to log in from the homepage or anywhere else in the app). One thing I have tried was to redirect unauthenticated users this way:
const session = await getServerAuthSession();
if (!session?.user) {
redirect(`/api/auth/signin?url=${env.NEXTAUTH_URL}/tickets/register`);
}
const session = await getServerAuthSession();
if (!session?.user) {
redirect(`/api/auth/signin?url=${env.NEXTAUTH_URL}/tickets/register`);
}
Which in my dev environment took me to: http://localhost:3000/api/auth/signin?url=http%3A%2F%2Flocalhost%3A3000%2F%2Ftickets%2Fregister However it still leads me back to homepage "/" after logging in. Does anyone have a better idea?
Solution:
Redirect them with them the callback url in the query parameter and use that on signIn? signIn({credentials, callbackUrl: url})...
Jump to solution
1 Reply
Solution
troy
troy7mo ago
Redirect them with them the callback url in the query parameter and use that on signIn? signIn({credentials, callbackUrl: url})
Want results from more Discord servers?
Add your server