Skip to content
Back to Deployment

Deploying Next.js Apps

SSR/SSG/ISR deployment for Next.js with image optimization, API routes, and middleware on Vercel or self-hosted.

PlatformsIntermediate

Why

Next.js supports hybrid rendering (SSG + SSR + ISR) in one framework, and Vercel (its creator) provides zero-config deploys with edge middleware and image optimization. Self-hosting via standalone output gives full control.

When

Use Next.js for SEO-sensitive marketing sites, e-commerce, and dashboards needing SSR. Self-host when you need custom infra or air-gapped environments.

How

1. Vercel path — git push, auto-detected, zero config 2. Self-host — next.config.js output: "standalone", produces .next/standalone 3. Docker — copy standalone + static to minimal image, node server.js 4. API routes — become serverless functions on Vercel, run in Node container self-hosted 5. Images — next/image uses Vercel's optimizer; self-host set images.unoptimized or custom loader 6. Middleware — runs on edge (Vercel) or Node (self-host), auth/geo/rewrites 7. ISR — revalidate prop re-generates pages on demand, needs persistent storage self-hosted

Example

// next.config.js — standalone output for self-hosting /** @type {import('next').NextConfig} */ module.exports = { output: "standalone", images: { unoptimized: process.env.SELF_HOSTED === "true" }, }; // Dockerfile (self-hosted) FROM node:20-alpine AS builder WORKDIR /app COPY . . RUN npm ci && npm run build FROM node:20-alpine WORKDIR /app 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"] // middleware.ts — edge auth export function middleware(req: NextRequest) { if (!req.cookies.get("token")) return NextResponse.redirect("/login"); } export const config = { matcher: ["/dashboard/:path*"] };

Common Problems

  • ⚠Self-hosted ISR loses cache on restart — no persistent storage, pages re-render cold
  • ⚠Image optimization 502 self-hosted — forgot to disable or configure sharp/loader
  • ⚠Middleware runs on Node instead of edge — older Next.js version or self-host without edge runtime

Best Practices

  • ✓Use output: 'standalone' for Docker deploys — produces minimal self-contained server
  • ✓Set images.formats to only what you need (avif, webp) to reduce optimization cost
  • ✓Set up health checks and graceful shutdown — handle SIGTERM to drain in-flight requests before exit

FAQ