Back to Home

NextAuth + Django JWT: unified authentication

The article describes integration of NextAuth with Django JWT for unified authentication without duplicate login. It covers custom user models, credentials provider, OAuth synchronization, and session optimization. Full working code is provided.

NextAuth and Django JWT without token chaos
Advertisement 728x90

NextAuth + Django JWT: Seamless Single Sign-On Without Duplication

NextAuth on Next.js and Django REST Framework with JWT often clash during authentication. Users log in once on the frontend, get access and refresh tokens from Django, and all API calls use a single client with automatic token refresh. OAuth providers sync with the backend—no second login screen needed.

Architecture Role Separation

NextAuth handles UI sessions, login forms, and OAuth. Django manages the user domain model, JWT issuance, and API protection via JWTAuthentication. The frontend never generates tokens itself—Django is the sole source of API access. Tokens are stored within the NextAuth session.

Key benefits of this setup:

Google AdInline article slot
  • No manual localStorage for access tokens
  • Automatic refresh without 401 errors
  • OAuth sync without duplicate logins
  • Single axios client for all requests

Django: Email-First User Model and Custom JWT

The user model uses email as USERNAME_FIELD. This simplifies OAuth integration, where usernames aren't always available.

# auth_app/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.contrib.auth.models import BaseUserManager

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError("The Email field must be set")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        return self.create_user(email, password, **extra_fields)


class User(AbstractUser):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=100, blank=True)
    provider = models.CharField(max_length=50, default="credentials", blank=True, null=True)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    objects = CustomUserManager()

In settings.py: AUTH_USER_MODEL = "auth_app.User". Install rest_framework_simplejwt, dj_rest_auth, and allauth.

Custom TokenObtainPairSerializer adds email, name, and provider to the token:

Google AdInline article slot
# auth_app/serializers.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token["email"] = user.email
        token["name"] = user.name
        token["provider"] = user.provider
        return token

    def validate(self, attrs):
        credentials = {
            "email": attrs.get("email"),
            "password": attrs.get("password"),
        }
        return super().validate(credentials)

Login view checks email verification and returns tokens + user data:

# auth_app/views.py
class CustomTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        user = serializer.user
        email_address = EmailAddress.objects.filter(user=user, email=user.email).first()
        if not email_address or not email_address.verified:
            raise AuthenticationFailed(detail="Email address is not verified.")

        return Response(
            {
                "access": serializer.validated_data["access"],
                "refresh": serializer.validated_data["refresh"],
                "user": {
                    "email": user.email,
                    "name": user.name,
                    "id": user.id,
                },
            },
            status=status.HTTP_200_OK,
        )

Next.js: Credentials Provider as Django Proxy

The Credentials provider forwards email/password to Django and stores the received tokens in the session:

// src/lib/auth/authOptions.ts
import { NextAuthOptions } from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import CredentialsProvider from "next-auth/providers/credentials";
import apiClient from "@/services/authClientService";

const baseURL = process.env.NEXT_PUBLIC_API_BASE_URL;

export const authOptions: NextAuthOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text" },
        password: { label: "Password", type: "password" },
      },
      async authorize(credentials) {
        if (!credentials?.email || !credentials.password) {
          throw new Error("Email and password must be provided");
        }

        const { data } = await apiClient.post(`${baseURL}/api/auth/custom/login/`, {
          email: credentials.email,
          password: credentials.password,
        });

        if (data?.user) {
          const { id, name, email } = data.user;
          return {
            id: id.toString(),
            name,
            email,
            accessToken: data.access || null,
            refreshToken: data.refresh || null,
          };
        }

        return null;
      },
    }),
  ],
};

OAuth Sync: register-or-login Endpoint

After Google OAuth, hit the register-or-login endpoint. Django creates or updates the user and issues JWT:

Google AdInline article slot
callbacks: {
  async signIn({ user, account }) {
    const allowedProviders = ["google", "apple"];

    if (account?.provider && allowedProviders.includes(account.provider)) {
      const res = await apiClient.post(
        `${baseURL}/api/auth/custom/oauth/register-or-login/`,
        {
          id: user.id,
          name: user.name,
          email: user.email,
          provider: account.provider,
        }
      );

      if (res.status === 200) {
        user.accessToken = res.data.access;
        user.refreshToken = res.data.refresh;
        return true;
      }

      return false;
    }

    return true;
  },
},

Django endpoint:

class CustomOAuthRegisterOrLoginView(APIView):
    permission_classes = [AllowAny]

    def post(self, request, *args, **kwargs):
        serializer = OAuthUserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data

        provider = data["provider"]
        email = data["email"]
        name = data["name"]
        user_id = data["id"]

        user, created = User.objects.get_or_create(
            email=email,
            defaults={
                "name": name,
                "provider": provider,
                "username": user_id,
            },
        )

        if not created:
            user.name = name
            user.provider = provider
            user.save()

        refresh = RefreshToken.for_user(user)
        access = str(refresh.access_token)

        return Response(
            {
                "message": "User successfully synchronized.",
                "user": {
                    "email": user.email,
                    "name": user.name,
                    "provider": user.provider,
                },
                "access": access,
                "refresh": str(refresh),
            },
            status=status.HTTP_200_OK,
        )

JWT and Session Callback Optimization

JWT and session store only id, accessToken, and refreshToken. Extra data is excluded to minimize size:

async jwt({ token, user }) {
  if (user) {
    token.id = user.id.toString();
    token.accessToken = user.accessToken || null;
    token.refreshToken = user.refreshToken || null;
  }
  return token;
},

async session({ session, token }) {
  session.user = {
    ...session.user,
    id: token.id as string,
  };
  session.accessToken = token.accessToken || null;
  session.refreshToken = token.refreshToken || null;
  return session;
},

Key Takeaways

  • Single token source: Django JWT is the only API access authority
  • Auto OAuth sync: register-or-login eliminates duplicate logins
  • Lean sessions: Just id + tokens, no bloat
  • Email verification: Built into login for consistency
  • Axios interceptor: Auto refresh and logout on 401

— Editorial Team

Advertisement 728x90

Read Next