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. The Auth.js docs aren’t super clear, so I’m stuck.

Here’s what I’m trying to figure out:

  1. How do I store and refresh JWT tokens using NextAuth.js?
  2. What’s the best way to make API calls that need authentication from my Next.js app?
  3. How can I make sure users log out properly?

I’ve got Djoser’s jwt/create/ endpoint set up, but I’m not sure how to connect all the pieces. Has anyone tackled this before? Any advice would be awesome!

hey iris72! i’m curious about your project. have u considered using a custom middleware in next.js to handle JWT stuff? it could simplify things. also, whats ur experience with djoser so far? any specific features you find tricky? maybe we could brainstorm some solutions together!

I’ve faced similar challenges integrating Next.js with Django and JWT authentication. Here’s what worked for me:

For storing and refreshing tokens, I implemented a custom JWT session provider in NextAuth.js. This allowed me to handle token storage and refreshing seamlessly.

For authenticated API calls, I created a custom axios instance with an interceptor. It automatically adds the JWT to requests and handles token refreshing when needed.

For proper logout, I found it crucial to clear both client-side storage and invalidate the token on the server. I implemented a custom logout function that handles both aspects.

The key is to create a cohesive authentication flow that bridges Next.js and Django. It takes some setup, but once in place, it works smoothly. Hope this helps point you in the right direction!

yo iris72, been there with jwt headaches! for storing tokens, try using httpOnly cookies. they’re safer than localStorage. for api calls, create a custom hook that adds the token to headers. logout? just clear the cookie and hit the backend to blacklist the token. hope this helps, mate!