A complete full-stack authentication implementation using Django REST Framework and Next.js with NextAuth.js. This project demonstrates a modern approach to building secure authentication systems with a Django backend API and a Next.js frontend.
- User Authentication: Complete email-based authentication flow
- Session Management: Secure session handling with NextAuth.js
- Token-based Auth: Django REST Framework token authentication
- User Registration: New user registration with django-allauth
- Protected Routes: Middleware-protected routes in Next.js
- CORS Configured: Properly configured CORS for cross-origin requests
- Modern UI: Clean, responsive UI built with Tailwind CSS
- Type Safety: Full TypeScript support on the frontend
- Django 4.2.6 - Python web framework
- Django REST Framework - RESTful API toolkit
- dj-rest-auth - Authentication REST APIs
- django-allauth - User registration and authentication
- django-cors-headers - CORS handling
- SQLite - Database (default, easily swappable)
- Next.js 14.0.0 - React framework
- NextAuth.js 4.24.4 - Authentication for Next.js
- TypeScript - Type-safe JavaScript
- Tailwind CSS - Utility-first CSS framework
- Axios - HTTP client for API requests
Before you begin, ensure you have the following installed:
- Python 3.8 or higher
- Node.js 18.x or higher
- npm or yarn package manager
- pip - Python package manager
git clone https://github.com/teamhashed/django-nextjs-auth.git
cd django-nextjs-auth
cd backend
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -r requirements.txt
Create a .env
file in the backend
directory:
DO NOT use these values in production! Replace all values with secure, production-appropriate settings.
DEBUG=True
SECRET_KEY=CHANGE-ME-IN-PRODUCTION
HTTP_ROUTE=rest/
CORS_ALLOWED_HOSTS=CHANGE-ME-IN-PRODUCTION
Important: Generate a secure SECRET_KEY
for production. You can generate one using:
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
The backend API will be available at http://localhost:8000/rest/
Open a new terminal and navigate to the frontend directory:
cd frontend
npm install
# or
yarn install
Create a .env.local
file in the frontend
directory:
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=REPLACE_ME_WITH_A_SECURE_SECRET
NEXTAUTH_BACKEND_URL=REPLACE_ME_WITH_YOUR_BACKEND_URL
Important: Generate a secure NEXTAUTH_SECRET
:
openssl rand -base64 32
npm run dev
# or
yarn dev
The frontend will be available at http://localhost:3000
django-nextjs-auth/
βββ backend/ # Django backend
β βββ creds/ # Custom user authentication app
β β βββ api/ # API views and serializers
β β βββ models.py # Custom User model
β β βββ ...
β βββ www/ # Main Django project
β β βββ settings.py # Django settings
β β βββ urls.py # URL configuration
β β βββ ...
β βββ manage.py # Django management script
β βββ requirements.txt # Python dependencies
β
βββ frontend/ # Next.js frontend
β βββ app/ # Next.js app directory
β β βββ api/ # API routes
β β β βββ auth/ # NextAuth configuration
β β βββ page.tsx # Home page
β β βββ layout.tsx # Root layout
β β βββ globals.css # Global styles
β βββ middleware.ts # Next.js middleware for auth
β βββ package.json # Node dependencies
β βββ ...
β
βββ .gitignore
βββ LICENSE
βββ README.md # This file
The Django backend exposes the following API endpoints:
- POST
/rest/api/v1/auth/login/
- User login - POST
/rest/api/v1/auth/logout/
- User logout - POST
/rest/api/v1/auth/register/
- User registration - GET
/rest/api/v1/auth/user/
- Get current user details - POST
/rest/api/v1/auth/password/change/
- Change password - POST
/rest/api/v1/auth/password/reset/
- Request password reset - GET
/rest/api/v1/auth/check-token/
- Validate authentication token
Access the Django admin panel at: http://localhost:8000/rest/admin/
- User Registration/Login: User submits credentials through Next.js frontend
- API Request: Frontend sends credentials to Django backend via NextAuth
- Token Generation: Django validates credentials and returns an authentication token
- Session Creation: NextAuth stores the token in a secure session
- Protected Routes: Middleware checks authentication status before rendering pages
- API Calls: Authenticated requests include the token in headers
The custom user model is defined in backend/creds/models.py
. You can extend it with additional fields:
class User(AbstractUser):
email = models.EmailField(unique=True)
# Add your custom fields here
phone_number = models.CharField(max_length=15, blank=True)
bio = models.TextField(blank=True)
Remember to create and run migrations after making changes:
python manage.py makemigrations
python manage.py migrate
The frontend uses Tailwind CSS. Customize the theme in frontend/tailwind.config.ts
.
cd backend
python manage.py test
cd frontend
npm run test
# or
yarn test
- Set
DEBUG=False
in your environment variables - Generate a strong
SECRET_KEY
- Configure your production database
- Set up proper
ALLOWED_HOSTS
- Collect static files:
python manage.py collectstatic
- Use a production WSGI server like Gunicorn or uWSGI
The easiest way to deploy the Next.js frontend is using Vercel:
cd frontend
npm run build
Alternatively, deploy to any platform that supports Node.js applications.
Ensure all environment variables are properly set in your production environment:
- Update
NEXTAUTH_URL
to your production domain - Set strong secrets for
SECRET_KEY
andNEXTAUTH_SECRET
- Configure
CORS_ALLOWED_HOSTS
with your frontend domain - Update
NEXTAUTH_BACKEND_URL
to your backend API URL
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature
) - Commit your changes (
git commit -m 'Add some AmazingFeature'
) - Push to the branch (
git push origin feature/AmazingFeature
) - Open a Pull Request
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
- Django REST Framework documentation
- Next.js documentation
- NextAuth.js documentation
- django-allauth for authentication functionality
For questions or issues, please open an issue on the GitHub repository.
Note: This is a development setup. For production use, ensure you follow security best practices, use environment-specific configurations, and properly secure your secrets.