Setting Up NextAuth.js with Django REST Framework and Djoser JWT Authentication

I’m working on a project where I need to connect my Django backend with a Next.js frontend for user authentication. Here’s what I’m using:

Backend setup:

  • Django REST Framework
  • Djoser package for handling JWT tokens

Frontend setup:

  • Next.js application
  • NextAuth.js for managing user sessions

I want my users to sign in through the Next.js app, which should then communicate with my Django API endpoint auth/jwt/create/ to get the authentication tokens. But I’m running into some issues and need help with a few things:

  1. How do I properly store and refresh JWT tokens when using NextAuth.js?
  2. What’s the best way to make API calls to my Django backend once a user is logged in?
  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 set up this kind of integration before?

interesting combo! Are you using nextAuth’s credentials provider or building smth custom? What errors are you getting when hitting /auth/jwt/create/? I’d love to hear more about your setup!

I set this up last year and ran into the same issues. The key is getting NextAuth’s JWT callback to work with Djoser’s token structure. Store both access and refresh tokens in the session callback, then add auto-refresh logic in the JWT callback when the access token dies. For API calls, use an Axios interceptor that handles token attachment and 401s by triggering refresh. When logging out, call NextAuth’s signOut AND your Django logout endpoint - you need both to kill the refresh token server-side. Once you get the callbacks talking to Djoser’s token lifecycle properly, everything runs way smoother.

i’ve done this setup b4. the key is getting nextAuth callbacks configured right to handle jwt refresh with djoser endpoints. also check ur django cors settings - make sure they allow your next.js domain. that’s what trips up most ppl.