Next.js Discord

Discord Forum

rotate jwt tokens use middleware or API routes?

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Avatar
Sun bearOP
Hi,

I am struggling to decide whether use middleware or API routes to rotate JWT access and refresh tokens in the cookies.

I have backed built in Django. When access token gets expire, Django send new access and refresh token. I am just confused that how to set new access and refresh token in the cookies. Should I use middleware or API routes?

Which is the best practise to do?

Thank you

9 Replies

Avatar
Korat
middleware is the place you would write the logic to call an endpoint for fetching the new tokens

route handler is the place you would create that internal endpoint to fetch those tokens.

you can do the whole thing in middleware but you cant do it just in api routes because they are different things
Avatar
Sun bearOP
@Korat thank you for your response

So should I combine those two or handle whole thing in middleware?
Avatar
Korat
If you handle all the stuff in the middleware, you don’t need api routes.

You can simply fetch those tokens from that external api inside the middleware
Avatar
Sun bearOP
Yes but will it create performance issue? This is my concern
Avatar
Korat
you need to be careful what you calculate in middleware and dont do heavy calculations, a simple if to check if jwt exp date has expired isnt bad for performance
An issue you might fall into is setting the cookies with the new tokens that the next request will use the new tokens but if you manage to pull that off let me know here
Avatar
Sun bearOP
Okay will check
Thanks for information
Avatar
Korat
happy to help