Setting Up Authentication Between Django REST Framework with Djoser and Next.js Using NextAuth

I’m working on a project where I need to connect my Django REST API with a Next.js frontend for user authentication.

My current setup:

  • Backend: Django REST Framework with Djoser handling JWT tokens
  • Frontend: Next.js with NextAuth for authentication management

I want my users to sign in through the Next.js app, which should then communicate with my Django API’s auth/jwt/create/ endpoint. The main issues I’m facing are:

  1. How do I properly store and refresh JWT tokens using NextAuth?
  2. What’s the best way to send authenticated requests to my Django API from the frontend?
  3. How should I handle the logout process to make sure tokens are cleared correctly?

The NextAuth documentation isn’t very clear about working with custom JWT backends like Djoser. Has anyone successfully implemented this kind of setup before? Any guidance would be really helpful.

been there! create a custom credentials provider in nextauth that calls ur djoser endpoint. store the access/refresh tokens in the session callback and use axios interceptors to automatically attach tokens to requests. for logout, just clear the nextauth session - works smoothly once u get it set up.

that’s a tricky combo to get working! have you tried nextauth’s custom provider feature instead of their standard jwt strategy? and why did you go with djoser over django’s built-in auth?

I encountered similar challenges while setting this up. One effective approach was to configure NextAuth’s JWT callback to manage token refresh automatically. It’s important to store both the access and refresh tokens in your NextAuth configuration while implementing token refresh logic in the JWT callback to execute before token expiration. For making API calls, I developed a custom fetch wrapper that includes the access token in the headers and automatically refreshes the token upon receiving a 401 error. During logout, utilize NextAuth’s signOut function to clear the session and consider invoking your Django logout endpoint to blacklist the refresh token, ensuring a comprehensive token lifecycle management without manual intervention.