Skip to content

Lesson 21 of 27Shipping

Deploying Next.js

Read the next build output, deploy to Vercel or your own Docker server, and wire up a database and monitoring.

16 min read0/4 questions

An app is not done until real users can reach it. Deploying Next.js well means knowing what next build actually produces, because that explains your hosting bill, why a page is unexpectedly slow, and why caching behaves differently on three containers than on your laptop. This lesson walks from the build output to Vercel, self-hosting with Docker, databases and monitoring.

What next build produces

next build compiles your app with Turbopack, prerenders every route it can, and writes everything to .next/. Then it prints a route table. With Cache Components enabled it looks like this:

Terminal
$ npm run buildRoute (app)                        Revalidate  Expire┌ ○ /                                     1h      1d├ ○ /pricing├ ◐ /blog/[slug]│ ├ /blog/hello-world│ └ /blog/shipping-nextjs├ ◐ /dashboard├ ƒ /api/webhooks/stripe└ ○ /sitemap.xml○  (Static)             prerendered as static content◐  (Partial Prerender)  prerendered as static HTML with dynamic server-streamed contentƒ  (Dynamic)            server-rendered on demand

Read it like this:

  • ○ Static: the whole route is HTML on disk. Serve it from a CDN; no server work per request. Revalidate and Expire columns show its cacheLife.
  • ◐ Partial Prerender: a static shell is prerendered, and the parts inside <Suspense> that need the request stream in at runtime. /blog/[slug] lists the slugs generateStaticParams built; other slugs get the shell first and are filled in on first visit.
  • ƒ Dynamic: rendered on every request. Route Handlers that read the request (like a webhook) and proxy.ts show up here.

Without Cache Components you will also see ● SSG: paths prerendered from generateStaticParams. If a route reads request data outside <Suspense>, the build fails and names the route; next build --debug-prerender gives a readable stack trace.

TypeScriptsummarize-build.ts
const output = `┌ ○ /├ ○ /pricing├ ◐ /blog/[slug]├ ◐ /dashboard├ ƒ /api/webhooks/stripe└ ○ /sitemap.xml`; const kinds: Record<string, string> = { "○": "static", "◐": "partial", "ƒ": "dynamic", "●": "ssg" };const counts: Record<string, number> = {};for (const line of output.split("\n")) { const m = line.match(/([○◐●ƒ])\s+(\/\S*)/); if (m) counts[kinds[m[1]]] = (counts[kinds[m[1]]] ?? 0) + 1;}console.log(counts);
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Your product page shows ƒ after a refactor, where it used to be ◐. What most likely changed?
Need a nudge? A hint rules out a wrong answer.

Deploying to Vercel

Vercel, the company behind Next.js, deploys it with no configuration:

  1. Connect your Git repository. Every push triggers next build on Vercel's build servers.
  2. Every branch and pull request gets a preview deployment with its own URL, so reviewers can click through the change before merging.
  3. Merging to the production branch (usually main) deploys to your domain.

Static output (○, and the shells of ◐ routes) is served from Vercel's global CDN. Dynamic rendering, streamed holes, Server Actions and Route Handlers run as functions that scale with traffic. ISR, use cache revalidation and image optimisation are handled by the platform.

Environment variables are set per environment in the project settings: Production, Preview and Development. Use separate databases or database branches for preview and production, and run vercel env pull to download the development values into .env.local. Remember from the previous lesson that NEXT_PUBLIC_ values are inlined at build time, so changing one needs a redeploy.

Runtimes. Next.js has two server runtimes: Node.js (the default, with every Node API) and the older Edge runtime (a restricted, web-API-only runtime). In current Next.js 16 the Edge runtime is deprecated for routes, proxy.ts runs on Node.js, and with Cache Components you do not set a runtime option at all. Write for Node.js.

Two common ways to run a Next.js app
VercelYour serversgit pushgit pushnext build: Vercel or CInext buildVercel or CICDN: static + shellsCDNstatic + shellsFunctions: dynamic, actionsFunctionsdynamic, actionsPostgres: Neon or SupabasePostgresNeon or Supabasenginx / LBnginx / LBDocker: next start: standaloneDocker: next startstandaloneRedis: shared cacheRedisshared cachebuilduploadmiss / holeSQLimageproxySQLcache

Every deploy starts with the same next build, on Vercel's builders or in your CI.

1/4

Self-hosting with next start and Docker

Next.js runs on any machine with Node.js (20.9 or newer):

npm run build   # next buildnpm run start   # next start: production server on port 3000

A plain next start server supports every feature: streaming, ISR, use cache, image optimisation, Server Actions, proxy. Put a reverse proxy such as nginx in front of it to handle TLS, slow clients, request size limits and rate limiting, and make sure the proxy does not buffer responses, or streaming and partial prerendering lose their benefit (for nginx, send the X-Accel-Buffering: no header).

For containers, set output: "standalone" in next.config.ts. The build then writes .next/standalone/, a minimal folder with a server.js and only the node_modules files your app actually uses, which makes images far smaller:

Dockerfile
FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
 
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
 
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
USER node
EXPOSE 3000
CMD ["node", "server.js"]
Put it in order5 steps

Put the standalone Docker build in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

There is also output: "export", which writes a fully static site you can host on S3 or GitHub Pages. It drops everything that needs a server (Server Actions, request-time rendering, proxy, default image optimisation), so it only suits fully static sites.

Caching and images when you self-host

On one server, everything just works: the Next.js cache (prerendered pages, ISR, cached data) lives in memory and on local disk, and next/image optimises images on demand with sharp. With several instances behind a load balancer, check four things:

  • Shared cache. Each container has its own disk, so one may serve a page another just revalidated. Configure a cache handler backed by shared storage such as Redis (cacheHandler for pages and ISR, cacheHandlers for use cache: remote).
  • Same build everywhere. Build once and run that image on every instance. If you rebuild per environment, set a consistent build ID with generateBuildId or a deploymentId.
  • Same Server Actions key. Set NEXT_SERVER_ACTIONS_ENCRYPTION_KEY so an action encrypted by one instance can be decrypted by another; otherwise users see "Failed to find Server Action".
  • CDN in front. Forward the Accept header for images (it picks WebP or AVIF) and respect the Cache-Control headers Next.js sets: long-lived immutable for hashed assets, and private, no-store for dynamic pages.
Quick check
You run four containers of the same app. After an admin calls revalidateTag("products", "max"), some users still see old prices for a long time. What is the likely cause?
Need a nudge? A hint rules out a wrong answer.

Databases

Most Next.js apps pair with Postgres. Two managed options are especially common:

  • Neon: serverless Postgres that scales to zero and supports branching, so each preview deployment can get its own copy of the database.
  • Supabase: Postgres plus auth, storage and realtime in one service.

Either works with ORMs like Drizzle or Prisma. One trap with serverless hosting: each function instance opens its own connection, and a traffic spike can exhaust Postgres's connection limit. Use the provider's pooled connection string (a connection pooler such as PgBouncer sits in front of the database) or its serverless HTTP driver. Run migrations as a step in CI, before the new code goes live, never at app startup on every instance.

Run the numbers for a traffic spike:

TypeScriptconnections.ts
const postgresMaxConnections = 100;const connectionsPerInstance = 5; // a typical ORM pool size per process for (const instances of [4, 20, 60]) { const direct = instances * connectionsPerInstance; const status = direct > postgresMaxConnections ? "too many connections" : "ok"; console.log(`${String(instances).padStart(2)} instances → ${String(direct).padStart(3)} direct connections: ${status}`);}console.log("with a pooler: instances share a fixed pool of, say, 20 real connections");
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/4 matched

Match the situation to the setup.

Choose an item, then its match on the other side.

Monitoring

Once it is live, you need to know when it breaks and when it is slow:

  • instrumentation.ts at the project root runs once when the server starts. Its register() function is where you set up OpenTelemetry tracing, and its onRequestError hook reports every server error with the route that caused it.
  • Error tracking such as Sentry captures server and client exceptions with stack traces and releases.
  • Real-user performance: useReportWebVitals from next/web-vitals, or the host's analytics (Vercel Speed Insights), records LCP, INP and CLS from actual visitors.
  • Logs: structured console output from functions or containers, shipped to your log platform.
instrumentation.ts
import { registerOTel } from "@vercel/otel";
 
export function register() {
  registerOTel({ serviceName: "acme-web" });
}
 
export async function onRequestError(error: unknown, request: { path: string; method: string }) {
  await fetch("https://errors.acme.dev/ingest", {
    method: "POST",
    body: JSON.stringify({ message: String(error), path: request.path, method: request.method }),
  });
}
ChallengeEasy

Read the next build route table

After next build, CI logs show a route table. Write parseBuildOutput(output) that turns it into data so a script can fail a deploy if, say, the home page stops being static.

Each route line has a symbol followed by spaces and a path starting with /:

Symbolkind
○"static"
◐"partial"
●"ssg"
ƒ"dynamic"

Return { route, kind } for every route line, in order. Ignore every other line, including the legend at the bottom (its symbol is followed by (Static), not a path). Extra columns after the path (like revalidate times) are not part of the route.

Route (app)
┌ ○ /
├ ◐ /products/[id]
└ ƒ /api/checkout
 
○  (Static)  prerendered as static content
TypeScript
type Row = { route: string; kind: "static" | "partial" | "ssg" | "dynamic" }; function parseBuildOutput(output: string): Row[] { return [];}
Key terms
route table
The next build summary that marks each route as static (○), partially prerendered (◐), SSG (●) or dynamic (ƒ).
preview deployment
A deployment of a branch or pull request at its own URL, used for review before merging.
standalone output
output: "standalone": a minimal .next/standalone folder with server.js, ideal for small Docker images.
cache handler
A configurable storage backend (such as Redis) for the Next.js cache, needed when several instances must share it.
connection pooling
Sharing a small number of database connections among many short-lived clients, essential for serverless Postgres.
instrumentation.ts
A root file whose register() runs at server start (tracing setup) and whose onRequestError reports server errors.