Muhammad
Muhammad

Reputation: 1

How to redirect to previous route after authentication (sing-in or sign-up) in clerk using it with nextjs

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

Answers (2)

Daniel Bryte
Daniel Bryte

Reputation: 1

Here is how to solve it, i was facing same issue, and the Clerk doc didn't explain well:

  1. On the page you want to redirect to after signing in import the "SignInButton" from clerk, e.g: import { SignInButton } from "@clerk/nextjs";

  2. Use this button without any route.push or link to sign-in page, just the "SignInButton" from clerk in the page itself.

  3. 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>
  1. Now after signing, it redirects you back to the fallback URL. Remember, also add a SignUp fallback URL as in my example in No.3 in case it's a new user.

You're welcome ;)

Upvotes: 0

Fakhrul Islam Fuad
Fakhrul Islam Fuad

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

Related Questions