workos / authkit-nextjs

The WorkOS library for Next.js provides convenient helpers for authentication and session management using WorkOS & AuthKit with Next.js.
MIT License
44 stars 9 forks source link

Implement Automatic Configuration for Redirecting Users After Login #11

Closed gorbulls456667 closed 3 months ago

gorbulls456667 commented 3 months ago

Is it feasible to implement automatic configuration for a parameter similar to 'afterSignInUrl,' ensuring that when a user attempts to access a protected page and then successfully logs in, they are redirected to the original page they were trying to reach?

For example:

  1. A user tries to access a restricted page on a website, such as "example.com/secure-page".
  2. They are redirected to the login page to authenticate (Authkit hosted page).
  3. After successfully logging in, they are automatically redirected back to "example.com/secure-page" instead of being directed to a default page ("/")
PaulAsjes commented 3 months ago

Hi @gorbulls456667, good timing! We're actually working on that right now: https://github.com/workos/workos-nextjs/pull/9

Once that PR lands you'll be able to provide a path in your callback route to redirect to after the user logs in:

export const GET = handleAuth({ returnPathname: '/dashboard' });

Similarly if your user tries to access a protected page (e.g. /admin) without being logged in, after authenticating via AuthKit they'll be redirected tot he page they were trying to access rather than /.

Does that solve your issue? If not we'd love to hear it as we're still figuring out the best API for this library.

gorbulls456667 commented 3 months ago

That sounds fantastic, and it seems like it'll solve the issue perfectly.

gorbulls456667 commented 3 months ago

I'm currently trying out the new package renamed @workos-inc/authkit-nextjs version 0.4.0 and I'm encountering an issue with post-login redirection within my next.js application.

Currently, the default returnPathname in the callback route, is functioning correctly:

export const GET = handleAuth({ returnPathname: "/dashboard" });

However, I've noticed that when I use

const { user } = await getUser({ ensureSignedIn: true });

in a protected page and then successfully log in, I'm not redirected to the page I was originally trying to reach, but rather to the default returnPathname set in the callback route.

It seems that the current behavior is not what is desired. Similarly, as @PaulAsjes mentioned, "if your user tries to access a protected page (e.g. /admin) without being logged in, after authenticating via AuthKit they'll be redirected to the page they were trying to access rather than /."