# Building Scalable Microservices with FastAPI and Next.js
Modern web architectures demand low latency, robust type safety, seamless user experiences, and asynchronous backend processing. Combining **FastAPI (Python)** on the backend with **Next.js 14 (React & TypeScript)** on the frontend delivers an exceptional developer experience and production performance.
In this deep-dive tutorial, we explore architectural patterns, JWT session authentication, API proxies, database abstraction with SQLAlchemy/Dapper, and Docker deployment strategies.
---
Architectural Overview
The decoupled microservices model relies on a high-throughput backend API service and an optimized, SSR/ISR capable frontend layer:
+---------------------+ +----------------------+ +---------------------+
| Next.js Client | <-----> | FastAPI Gateway | <-----> | PostgreSQL / DB |
| (App Router & React)| HTTP | (Pydantic & Async) | SQL/ORM | (User & App Data) |
+---------------------+ +----------------------+ +---------------------+Key Architectural Benefits: 1. **Asynchronous I/O:** FastAPI leverages Python's `asyncio` and Starlette, delivering handling speed comparable to Node.js and Go. 2. **Automatic OpenAPI (Swagger) Docs:** Built-in Pydantic schema validation generates interactive API documentation effortlessly. 3. **Next.js App Router:** Offers Server-Side Rendering (SSR), Incremental Static Regeneration (ISR), and optimized API route handlers.
---
Backend Implementation: FastAPI & Pydantic V2
Setting up a clean controller and service structure ensures maintainability:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, EmailStrapp = FastAPI( title="Core Portfolio API", version="1.0.0", docs_url="/docs" )
app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
class UserLogin(BaseModel): email: EmailStr password: str
@app.post("/api/v1/auth/login") async def login(credentials: UserLogin): # Authenticate credentials and issue JWT return {"access_token": "token_string", "token_type": "bearer"} ```
---
Secure Authentication & Token Refresh Flow
Implementing secure JWT authentication requires separating short-lived access tokens from long-lived HTTP-only refresh cookies.
1. **Access Token:** Short lifespan (e.g., 15 minutes), passed via `Authorization: Bearer <token>`. 2. **Refresh Token:** Stored in an `HttpOnly`, `Secure`, `SameSite=Lax` cookie to mitigate XSS vulnerabilities. 3. **Frontend Interceptor:** Standardize client requests with automatic token refresh on 401 Unauthorized responses.
---
Deployment & Containerization with Docker
Deploying a FastAPI + Next.js stack with Docker guarantees environmental consistency:
version: '3.8'services: backend: build: ./backend ports: - "8000:8000" environment: - DATABASE_URL=postgresql://user:pass@db:5432/maindb - SECRET_KEY=your_production_secret
frontend: build: ./frontend ports: - "3000:3000" environment: - NEXT_PUBLIC_API_URL=https://api.khanalmilan.com.np ```
---
Conclusion & Best Practices
- Always sanitize input using Pydantic validation schemas. - Implement rate limiting (e.g., `slowapi`) to defend against brute-force attacks. - Use ISR (`revalidate`) in Next.js for high-volume content pages to maximize speed and AdSense SEO indexability.