Next.js Discord

Discord Forum

Understanding how to store JWT tokens

Unanswered
Cinnamon posted this in #help-forum
Open in Discord
Avatar
CinnamonOP
Hi, I am doing a hobby project and I decided to try and setup my own authentication and authorization using JWT. Everything is working on my backend (FastAPI) but im struggling to store the access and refresh token in my nextjs app.

I have a signin form that calls a server action. This server action ends up storing the access and refresh tokens in a http only cookie. Everything is fine. In my middleware and server components I can get the cookie and fetch the data I need from my backend in client and server components. But then I start to see a lot of issues that I am not really sure how to tackle.

First of all, lets forget about the client and focus on the server:
The access token expires each 30 minutes. I handle the refresh by checking if a request made by a server component returns a 401. Then I refresh the token and I have no clue how to set the new cookie as servers component cannot set cookies. I read that I could set cookies in route handlers, so I figured out that I could do the backend fetching in a route handler that will be called by the server component. But then the cookie is not stored in the browser as the request is done in the server side of next due to the server component. No clue how to store the refreshed access and refresh tokens on request made by a server component.

I guess that for client components I could use the route handler method as this time the request is made by the browser so 'Set-Cookie' would work but are there any other recommendations?

I know I could use nextauth or other libraries to handle this stuff but I would like to implement it myself but It seems I am missing something specially in the server side.

0 Replies