Next.js 15 with React Server Components and a Django backend is one of the most productive combinations for products that need both a rich, fast frontend and a robust data layer. Django gives you the ORM, admin, authentication, and business logic. Next.js gives you server rendering, excellent SEO, and a modern component model. The challenge is wiring them together cleanly. This guide covers project structure, authentication, data fetching, forms, SEO, and deployment.
First, make sure you actually need this stack; our comparison of React vs Django templates explains when plain Django is the better call. If you are coming from an older React app, see migrating from Create React App to Next.js.
- Project structure: monorepo or separate repos
- Authentication: the JWT flow
- Forms with Server Actions
- Deployment
Project structure: monorepo or separate repos
For a small team, a monorepo with two top-level folders works well: backend/ (Django) and frontend/ (Next.js), with shared docs and a single CI pipeline. It makes cross-cutting changes, such as adding an API field and using it in the UI, a single pull request. Separate repositories make sense when different teams own each side or deploy cadences differ significantly. Either way, treat the API as the contract and version it, as we describe in API integration patterns for Django.
Architecture overview
Browser
|
v
Reverse proxy (Nginx / Cloudflare)
|-- /api/*, /admin/*, /static/* --> Django (Gunicorn :8000)
| |
|-- everything else --> Next.js (Node :3000)
| Server Components fetch
v
Django REST API (internal URL)
|
v
PostgreSQL / Redis
The browser talks to one domain. Next.js runs on the server and calls Django over the internal network, so API calls from Server Components never cross the public internet and never expose internal URLs.
Next.js runs on the server and calls Django over the internal network, so API calls from Server Components never cross the public internet and never expose internal URLs.
Authentication: the JWT flow
A robust pattern uses short-lived JWT access tokens and refresh tokens, stored in HttpOnly, Secure, SameSite cookies so JavaScript cannot read them.
- The login form posts to a Next.js route handler or Server Action.
- That handler calls Django's token endpoint (for example with
djangorestframework-simplejwt) and receives tokens. - Next.js sets them as HttpOnly cookies.
- Next.js middleware checks the cookie on protected routes and redirects unauthenticated visitors to login. When the access token is expired, it uses the refresh token and rewrites cookies.
- Server Components read the cookie and pass it as a Bearer token when calling Django.
Because middleware runs at the edge on every request, keep it light: verify token presence and expiry, and leave authorization decisions to Django, which remains the source of truth.
Because middleware runs at the edge on every request, keep it light: verify token presence and expiry, and leave authorization decisions to Django, which remains the source of truth.
Data fetching from Server Components
A Server Component can be an async function that fetches directly:
// app/projects/page.tsx
async function getProjects() {
const res = await fetch(`${process.env.API_URL}/api/v1/projects/`, {
next: { revalidate: 300, tags: ["projects"] },
});
if (!res.ok) throw new Error("Failed to load projects");
return res.json();
}
export default async function Page() {
const projects = await getProjects();
return <ProjectList items={projects.results} />;
}
Caching strategies
The next.revalidate option sets time-based revalidation, while tags enable on-demand invalidation. When an editor saves a project in Django, a signal can call a Next.js revalidation endpoint with a shared secret, which calls revalidateTag("projects"). Content updates go live in seconds while visitors still get cached pages.
Want expert help with this? Let's make it happen.
Get a Free ConsultationRendering mode comparison
| Mode | When HTML is built | TTFB | Freshness | Best for |
|---|---|---|---|---|
| SSG (static) | At build time | Fastest | Stale until rebuild | Marketing pages, docs |
| ISR | At build, then regenerated on a schedule or on demand | Fast (cached) | Near-real-time | Catalogs, blogs, listings |
| SSR (dynamic) | On every request | Slower (depends on API) | Always fresh | Dashboards, personalized pages |
Use ISR as your default for public content, SSR for authenticated or user-specific pages, and SSG only for content that rarely changes.
Forms with Server Actions
Server Actions let a form submit to a server function without writing a separate API route. The action validates input, calls the Django endpoint with the user's token, handles errors from the Django error envelope, and calls revalidatePath or revalidateTag on success. Keep validation on both sides: Next.js for fast feedback, Django as the authority. Surface Django's field errors by mapping the response back to the form state.
SEO: metadata, sitemap, Open Graph
- Metadata API: use
generateMetadatato build titles, descriptions, canonical URLs, and Open Graph tags from the same API data used to render the page. - Sitemap: create
app/sitemap.tsthat fetches slugs from Django and returns URLs with last-modified dates. - Structured data: render JSON-LD in a script tag from server components.
- Open Graph images: generate dynamically with
opengraph-image.tsx.
Deployment
Run Django and Next.js as separate containers or services behind one reverse proxy. Route /api/, /admin/, and static files to Django, and the rest to Next.js. Set an internal API_URL for server-side fetches and rely on same-origin requests from the browser, which removes most CORS complexity and keeps cookies simple. Deploy them independently, but keep backward-compatible API changes so either side can roll back.
The result is a stack where each layer does what it does best. If you want an experienced hand designing and building it, our custom web development service covers both the Django and Next.js sides.
Related reading: Migrating from Create React App to Next.js | React vs Django Templates: When to Use Which | API Integration Patterns for Django Applications
Planning a Next.js frontend on top of Django? Explore my custom web development service or get in touch for a free consultation.
Frequently Asked Questions
Can Next.js Server Components call Django directly?
Yes. Server Components run on the server, so they can fetch from Django's REST API over an internal URL, forward the user's token, and return finished HTML to the browser without exposing the API address.
Where should I store JWTs in a Next.js and Django app?
Store them in HttpOnly, Secure, SameSite cookies set by Next.js, not in localStorage. This keeps tokens inaccessible to client-side JavaScript and reduces XSS risk.
Is Next.js with Django better than Django templates?
Not always. Choose Next.js when you need highly interactive interfaces, a shared component library, or advanced rendering strategies. For content sites and standard CRUD apps, Django templates with HTMX are simpler and cheaper to maintain.
Full-stack разработчик, специализирующийся на Django, ИИ-автоматизации и управлении Google Ads. Создаю production SaaS платформы и кастомные веб-приложения для бизнеса по всей территории США.