Shipping a Next.js application to production involves far more than running a single command. This tutorial walks through everything from preparing your codebase to choosing a hosting strategy, securing your app, and keeping it observable once it's live. Whether you're deploying to Vercel, a Docker container, or a Kubernetes cluster, you'll find a practical, production-ready path here.
Information
đ 1. Introduction
Next.js supports multiple deployment models: fully managed platforms, self-hosted Node.js servers, containerized environments, and static exports. The right choice depends on your app's rendering strategy (SSR, SSG, ISR, or Edge), team expertise, and infrastructure constraints.
Tip
đ§° 2. Preparing for Deployment
Before deploying, audit your project for production-readiness. This includes dependency hygiene, environment configuration, and verifying that your app builds cleanly.
- Ensure next, react, and react-dom versions are compatible and up to date.
- Remove unused dependencies and dev-only packages from production bundles.
- Confirm all environment variables are documented in .env.example.
- Run next lint and fix warnings that could indicate runtime issues.
- Test the app locally using a production build, not just next dev.
Warning
đī¸ 3. Production Build
Next.js compiles your application into an optimized production bundle using the build command. This process performs code splitting, minification, static generation, and prerendering where possible.
Creating a production build
npm run build
# or
pnpm build
# or
yarn buildAfter building, start the optimized server locally to verify everything works as expected:
Starting the production server
npm run startNote
â 4. Production Checklist
Use this checklist before pushing to production to catch common oversights.
| Category | Check | Priority |
|---|---|---|
| Build | Production build completes with zero errors | Critical |
| Environment | All required env vars set on the host | Critical |
| Security | No secrets exposed via NEXT_PUBLIC_ prefix | Critical |
| Performance | Images optimized via next/image | High |
| SEO | Metadata and sitemap.xml configured | Medium |
| Monitoring | Error tracking and logging enabled | High |
Ⲡ5. Vercel Deployment
Vercel is the creator of Next.js and offers zero-configuration deployment with automatic CI/CD, edge caching, and preview URLs for every pull request.
Deploying via the Vercel CLI
npm i -g vercel
vercel login
vercel --prodBest Practice
đĨī¸ 6. Self-Hosting
Self-hosting gives you full control over infrastructure, at the cost of managing servers, scaling, and updates yourself. Next.js supports three self-hosting strategies:
Important
đĸ 7. Node.js Deployment
The simplest self-hosted approach runs Next.js as a long-lived Node.js process behind a process manager.
Standard Node.js deployment
npm run build
npm run start -- -p 3000For production resilience, use a process manager like pm2 to handle crashes, restarts, and clustering.
Running with PM2
npm i -g pm2
pm2 start npm --name "next-app" -- start
pm2 save
pm2 startupTip
đŗ 8. Docker Deployment
Containerizing your Next.js app ensures consistent environments across development, staging, and production.
Multi-stage Dockerfile
FROM node:20-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]Build and run the container
docker build -t next-app .
docker run -p 3000:3000 next-appBest Practice
â¸ī¸ 9. Kubernetes Deployment
For applications requiring horizontal scaling, self-healing, and rolling updates, Kubernetes orchestrates your containerized Next.js app across a cluster of nodes.
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: next-app
spec:
replicas: 3
selector:
matchLabels:
app: next-app
template:
metadata:
labels:
app: next-app
spec:
containers:
- name: next-app
image: your-registry/next-app:latest
ports:
- containerPort: 3000
env:
- name: NODE_ENV
value: "production"
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"service.yaml
apiVersion: v1
kind: Service
metadata:
name: next-app-service
spec:
selector:
app: next-app
ports:
- port: 80
targetPort: 3000
type: LoadBalancerNote
đĻ 10. Static Export
If your app has no server-side requirements (no API routes, no dynamic SSR), you can export it as fully static HTML, deployable to any static host or CDN.
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "export",
};
module.exports = nextConfig;Generating the static export
npm run build
# Output is generated in the "out" directoryCaution
đ 11. Edge Deployment
Edge runtimes execute code close to the user, reducing latency for personalization, authentication checks, and lightweight rendering logic.
Enabling the Edge runtime in a route
export const runtime = "edge";
export async function GET(request) {
return new Response("Hello from the edge!");
}Information
⥠12. Serverless Deployment
Serverless functions scale automatically and charge per invocation, making them cost-effective for variable traffic patterns. Platforms like Vercel, AWS Lambda, and Netlify Functions all support this model natively for Next.js.
| Model | Cold Starts | Best For |
|---|---|---|
| Serverless (Node.js) | Moderate | Full Node.js API access, SSR pages |
| Edge Functions | Minimal | Low-latency, lightweight logic |
| Long-Running Server | None | Predictable, high-throughput traffic |
đ 13. Environment Variables
Next.js loads environment variables from .env files at build and runtime. Variables prefixed with NEXT_PUBLIC_ are exposed to the browser; all others remain server-only.
.env.production
DATABASE_URL=postgres://user:pass@host:5432/db
NEXT_PUBLIC_API_URL=https://api.example.com
SESSION_SECRET=your-secret-hereDanger
đ 14. Domains
Once deployed, point a custom domain at your hosting provider by updating DNS records.
- Add an A record pointing to your host's IP, or a CNAME for platforms like Vercel.
- Configure both the apex domain (example.com) and www subdomain.
- Set up a redirect so one variant (usually www) canonically redirects to the other.
Tip
đ 15. HTTPS & SSL
Serving your app over HTTPS is non-negotiable for production. Most managed platforms provision SSL certificates automatically via Let's Encrypt.
For self-hosted deployments, tools like certbot automate certificate issuance and renewal:
Provisioning a certificate with Certbot
sudo certbot --nginx -d example.com -d www.example.comImportant
đŠī¸ 16. CDN Integration
A CDN caches static assets and, in some setups, full pages, at edge locations worldwide, reducing latency and origin load.
Tip
đ 17. Reverse Proxy
A reverse proxy sits in front of your Next.js server, handling SSL termination, load balancing, and routing to multiple backend instances.
âī¸ 18. Nginx Configuration
A minimal Nginx configuration proxies incoming requests to your Node.js process running on a local port.
/etc/nginx/sites-available/next-app
server {
listen 80;
server_name example.com www.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}Note
đī¸ 19. Performance Optimization
Production performance depends on how well you leverage Next.js's built-in optimization features.
- Use next/image for automatic image resizing, lazy loading, and modern format conversion.
- Use next/font to self-host fonts and eliminate layout shift.
- Enable ISR for pages with semi-static content to avoid full rebuilds.
- Analyze bundle size with @next/bundle-analyzer to catch bloat early.
- Leverage React.lazy and dynamic imports for code splitting on heavy components.
Tip
đĄī¸ 20. Security Best Practices
| Area | Recommendation |
|---|---|
| Headers | Set Content-Security-Policy, X-Frame-Options, and Referrer-Policy |
| Dependencies | Run npm audit regularly and patch known vulnerabilities |
| Secrets | Store secrets in a vault or platform-managed environment variables |
| Input Validation | Validate and sanitize all data in API routes and Server Actions |
| Rate Limiting | Protect public APIs and forms from abuse |
Important
đ 21. Monitoring
Monitoring gives you visibility into your app's health: response times, error rates, and resource usage.
Built into Vercel deployments, tracking Core Web Vitals and real-user performance metrics automatically with zero configuration.
An error-tracking platform that captures exceptions, stack traces, and performance traces across both client and server code.
A full-stack observability platform combining metrics, logs, and traces, well-suited for larger self-hosted infrastructures.
đ 22. Logging
Structured logs make debugging production issues far easier than scattered console.log calls.
Structured logging example
console.log(JSON.stringify({
level: "info",
message: "User logged in",
userId: user.id,
timestamp: new Date().toISOString(),
}));Tip
đ 23. Analytics
Analytics track user behavior and business metrics, distinct from performance monitoring. Popular options include Vercel Analytics, Google Analytics, and Plausible.
Example
đ 24. CI/CD Pipelines
A CI/CD pipeline automates testing, building, and deploying your app whenever code changes.
đ 25. GitHub Actions
GitHub Actions can automate builds and deployments directly from your repository.
.github/workflows/deploy.yml
name: Deploy Next.js App
on:
push:
branches: [main]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build application
run: npm run build
- name: Deploy
run: npx vercel --prod --token=${{ secrets.VERCEL_TOKEN }}Best Practice
đˇī¸ 26. Versioning
Tag each production release to maintain a clear history and enable quick rollbacks.
Tagging a release
git tag -a v1.4.0 -m "Release 1.4.0: add checkout flow"
git push origin v1.4.0Tip
âŠī¸ 27. Rollbacks
Even with careful testing, production issues happen. A fast rollback strategy minimizes downtime.
- On managed platforms like Vercel, use the dashboard to instantly promote a previous deployment to production.
- On self-hosted setups, keep the previous Docker image tagged and ready to redeploy.
- In Kubernetes, run kubectl rollout undo deployment/next-app to revert to the prior revision.
Warning
đ 28. Common Deployment Issues
| Issue | Likely Cause | Fix |
|---|---|---|
| Blank page after deploy | Missing environment variables | Verify all required vars are set on the host |
| 500 errors on API routes | Unhandled exceptions or DB connection issues | Check server logs and connection strings |
| Stale content | Aggressive CDN caching | Adjust Cache-Control or trigger revalidation |
| Large bundle size | Unoptimized imports | Use dynamic imports and analyze the bundle |
| Build fails in CI, works locally | Node version mismatch | Pin the Node.js version in CI config |
â 29. Frequently Asked Questions
Question
Answer
Question
Answer
Question
Answer
đ 30. Summary
Deploying a Next.js application successfully means matching your rendering strategy to the right hosting model, securing the app with HTTPS and proper headers, automating releases through CI/CD, and maintaining visibility through monitoring and logging once live.
Summary
- Choose a hosting model that fits your rendering needs: managed, self-hosted, static, or serverless.
- Always build and test a production bundle before deploying.
- Secure environment variables, enforce HTTPS, and set protective headers.
- Automate deployments with CI/CD and keep a fast rollback path ready.
- Monitor, log, and analyze your app continuously after launch.