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.
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:
$ 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 demandRead 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 itscacheLife.◐Partial Prerender: a static shell is prerendered, and the parts inside<Suspense>that need the request stream in at runtime./blog/[slug]lists the slugsgenerateStaticParamsbuilt; 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) andproxy.tsshow 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.
Press Run (⌘ Enter) to see what happens.ƒ after a refactor, where it used to be ◐. What most likely changed?Deploying to Vercel
Vercel, the company behind Next.js, deploys it with no configuration:
- Connect your Git repository. Every push triggers
next buildon Vercel's build servers. - Every branch and pull request gets a preview deployment with its own URL, so reviewers can click through the change before merging.
- 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.
Every deploy starts with the same next build, on Vercel's builders or in your CI.
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 3000A 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:
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 the standalone Docker build in order.
- Tap the steps below in the right order.
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 (
cacheHandlerfor pages and ISR,cacheHandlersforuse 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
generateBuildIdor adeploymentId. - Same Server Actions key. Set
NEXT_SERVER_ACTIONS_ENCRYPTION_KEYso an action encrypted by one instance can be decrypted by another; otherwise users see "Failed to find Server Action". - CDN in front. Forward the
Acceptheader for images (it picks WebP or AVIF) and respect theCache-Controlheaders Next.js sets: long-livedimmutablefor hashed assets, andprivate, no-storefor dynamic pages.
revalidateTag("products", "max"), some users still see old prices for a long time. What is the likely cause?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:
Press Run (⌘ Enter) to see what happens.Match the situation to the setup.
Monitoring
Once it is live, you need to know when it breaks and when it is slow:
instrumentation.tsat the project root runs once when the server starts. Itsregister()function is where you set up OpenTelemetry tracing, and itsonRequestErrorhook 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:
useReportWebVitalsfromnext/web-vitals, or the host's analytics (Vercel Speed Insights), records LCP, INP and CLS from actual visitors. - Logs: structured
consoleoutput from functions or containers, shipped to your log platform.
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 }),
});
}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 /:
| Symbol | kind |
|---|---|
○ | "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- route table
- The
next buildsummary 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/standalonefolder withserver.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 whoseonRequestErrorreports server errors.