Next.js Discord

Discord Forum

JWT Authentication flow with new App router

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hey all

I'm building a small app that needs some authentication to verify a user. I'm building the following flow:

- App checks if JWT token exists, if not, redirects to login page
- User enters email in a login form and submits
- User is looked up in db, if exists, generates a jwt token for that user and emails it with a "magic link"
- When magic link is opened, token is verified and then stored.

However, I'm a little lost on what would be the most optimal flow with server and client components and where to store what.

Currently I'm doing
- token is set in context which is in a client component (and fetched from window.sessionStorage)
- login form submits to a server action which generates the token and emails it
- magic link page is a client component that gets the token from search params
- sends a fetch request to a route handler that verifies it
- if verified, then sets the token in the context state (and also in window.sessionStorage)
- Redirects the user back to the home page.

Those last 3 steps feel kinda clunky... Using a client component to then send an xhr request to verify it... I'd rather have the magic link page be a server component that can immediately verify the token, but then it can't update state...

What would be the best way of handling this? Setting the jwt token in a cookie and checking that server side?

0 Replies