Reputation: 1
I want to go back to previous route after sign-in in my web app created with Nextjs. As the clerk documentation mentions, that we should provide
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
```in .env.local file.
But I want to go back to previous route.
Thanks.
I can't achieve my purpose.
Upvotes: 0
Views: 2505
Reputation: 1
Here is how to solve it, i was facing same issue, and the Clerk doc didn't explain well:
On the page you want to redirect to after signing in import the "SignInButton" from clerk, e.g: import { SignInButton } from "@clerk/nextjs"
;
Use this button without any route.push or link to sign-in page, just the "SignInButton
" from clerk in the page itself.
You need to use a fallbackRedirectUrl
or a forceRedirectUrl
on the clerk imported button.
e.g
<button>
<SignInButton fallbackRedirectUrl="/events/create" signUpFallbackRedirectUrl="/events/create" >
Create Event</SignInButton>
</button>
You're welcome ;)
Upvotes: 0
Reputation: 921
You can simply enable redirect using Environment variables
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/dashboard
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/welcomepage
But I guess the middleware option might be more reliable and efficient over other methods as it's more dynamic and will allow you to set dynamic redirect pathnames:
import { clerkMiddleware } from '@clerk/nextjs/server';
export default clerkMiddleware((auth, req) => {
if (req.nextUrl.pathname.startsWith('/dashboard')) auth().protect();
});
export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
you can get the requested pathname inside of the middleware and then set it as request header and then redirect to that request header. for this, you'll need multiple middleware which is called middleware chaining. check this answer if you need further help with middleware chaining
Although they're allowing some other ways to redirect:
Happy Hacking!!
Upvotes: 0