I’m currently developing a Next.js application coupled with a custom backend written in .NET.
My current authentication workflow involves:
- User authentication using a username and password.
- Upon successful authentication, I receive an access token and a refresh token from the server. These tokens, along with user information, are stored in cookies. Additionally, I store the access token exclusively in the browser’s local storage.
However, I’m facing a challenge when it comes to token refreshing. In the event of receiving a 401 Unauthorized error from the server, typically indicating an expired access token, I attempt to refresh the token. However, I’m struggling with synchronizing the local storage with the updated access token.
Furthermore, I’ve implemented middleware to protect my application routes, but currently, it only checks for the presence of the user’s cookie.
I would greatly appreciate any suggestions or guidance on how to address these challenges effectively.
Thank you!
Note: I’m using Nextjs 14 with app router
2
Answers
Why you don’t uses NextAuth:
Basic Authentications Flow: https://next-auth.js.org/providers/credentials
Refresh Token Flow: https://next-auth.js.org/v3/tutorials/refresh-token-rotation
https://authjs.dev/
You can use authjs for custom or social credentials.