Combining Next.js Frontend with Django Djoser Backend: Auth.js Integration Tips?

Hey everyone, I’m working on a project that’s giving me a headache. I’m trying to set up user login with Next.js on the frontend and Django with Djoser for JWT auth on the backend. I’m using Auth.js (NextAuth) but I’m totally lost.

My main issues are:

  1. How do I store and refresh JWT tokens using NextAuth?
  2. What’s the best way to make API calls that need authentication?
  3. I’m not sure how to handle logout correctly.

I’ve been digging through the Auth.js docs but they’re not super clear on this stuff. Has anyone done something similar? Any tips or code examples would be awesome. Thanks!

yo jumpingbear, i feel ur pain! hve u looked into using custom providers in nextauth? it lets u handle JWT stuff urself. for API calls, u can wrap fetch with a helper that adds the token. logout is tricky but clearing cookies n redirecting usually works. gl with ur project!

hey there! have you considered using axios interceptors for handling api calls and token refreshes? it’s pretty nifty! also, for logout, you could try invalidating the token on the backend. btw, how are you liking next.js so far? i’m curious about your experience combining it with django!

I’ve implemented a similar setup in a recent project. For JWT token management, I recommend using the jwt callback in NextAuth to handle token storage and refreshing. This allows you to customize the token’s payload and lifespan.

For authenticated API calls, create a custom Axios instance with an interceptor. This can automatically add the token to requests and handle refreshes when needed.

Regarding logout, ensure you clear both client-side storage (cookies, localStorage) and invalidate the token on the server. This two-pronged approach prevents lingering sessions.

One crucial tip: implement proper error handling for token expiration and network issues. It significantly improves user experience in real-world scenarios.