Part 18 / Stage 5
Deployment and observability
Goal: Build and run a real production bundle of this harness entirely on this machine —
next build,output: "standalone",node .next/standalone/server.js,instrumentation.ts— and be explicit, line by line, about which claims below were actually observed running locally versus documented from the installed Next.js docs without ever deploying anywhere. This part does not deploy to any platform, create any account, or touch any external service — that restriction is deliberate, stated by the person running this content wave, not a limitation this part works around quietly. Time: ~6 h · Level: finished Part 17 (npm run lint && npm run typecheck && npm run test && npm run buildall clean) Verified against: Next.js 16.4.6 / React 19.3.0, this same harness,output: "standalone"added tonext.config.tsfor this part. Every transcript below is real output from this exact install; see section 0 for the honesty split.
What you will learn
npm run build's own route table, read correctly, andoutput: "standalone"— what it actually produces, measured (62 MB vs. a 549 MBnode_modules), not just described- A real, surprising finding: the SQLite file
output: "standalone"'s file tracer bundles is a build-time snapshot, physically separate from your project's own database file — reproduced by writing through a running standalone server and checking both files - A second real finding in the same area:
.env.localisn't loaded for a standaloneserver.jsthe waynext dev/next startload it for themselves — and becauseproxy.ts's whole module graph gets evaluated per request regardless of its ownmatcher, a missing secret breaks every route, not just the ones the matcher names next startactively warns whenoutput: "standalone"is set, but still works directly off.next/either way — the warning is about redundant usage, not a real incompatibilityinstrumentation.ts'sregister()/onRequestError()hooks, firing for real against a deliberately-thrown error, plus a real Edge-vs-Node-runtime build warning and its fix- What this part only documents from the installed docs, never runs: multi-instance cache coordination, version skew/
deploymentId, the Server Functions encryption key, CDN/reverse-proxy streaming behavior, and the platform-by-platform deployment options table
Topics in this part
Practice
Every exercise below runs entirely on this machine, against this harness — none of them touch a real deployment platform or external service, matching this part's own scope. Several start and stop a node .next/standalone/server.js process on a scratch port (3101/3102/3103 below, change if any are already in use) — always confirm the port is free afterward (lsof -ti:PORT) before moving on.
Exercise 1: Confirm public/.next/static really are required — and that a running server needs a restart to pick them up
Scenario: Section 2's README asserts that skipping the two cp commands breaks static assets. Confirm it concretely, with a real missing asset — and check a second, non-obvious detail: whether copying the files into an already-running server's folder is enough, or whether the process needs to restart.
What to do: Run npm run build, then start node .next/standalone/server.js (set PORT/SESSION_PASSWORD as section 2 shows) without running either cp command first. Request the home page, grab a real _next/static/chunks/*.js filename from its HTML, and request that chunk directly. Then, without stopping the running server, run both cp commands and request the exact same chunk again. Finally, stop and restart the server and request it once more.
Sample output (run for real against this harness):
$ PORT=3101 SESSION_PASSWORD=<real value> node .next/standalone/server.js # no cp yet
$ curl -s http://localhost:3101/ -o /tmp/home.html
$ grep -o '_next/static/chunks/[^"]*\.js' /tmp/home.html | head -1
_next/static/chunks/1pcw6gskne7pf.js
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3101/_next/static/chunks/1pcw6gskne7pf.js
404
$ cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/ # server still running, not restarted
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3101/_next/static/chunks/1pcw6gskne7pf.js
404
# stop the server, start it again (same PORT/SESSION_PASSWORD) — no new build, same files on disk
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3101/_next/static/chunks/1pcw6gskne7pf.js
200
💡 Hint: Copying the files in while the server keeps running is not enough — confirmed directly: the exact same request stayed a 404 right after the cp commands finished, with the files genuinely present on disk (ls .next/standalone/.next/static/chunks/ shows them). Only after stopping and restarting the process did the same request return 200. The practical rule this proves: run both cp commands before starting server.js for the first time — don't assume a static-file add is picked up live the way editing a page during next dev would be.
Exercise 2: Reproduce the missing-env-var failure on a route genuinely outside the matcher
Scenario: Section 5 used / and /quickcart. Confirm the same failure on a third, clearly-unrelated route, to rule out a coincidence specific to those two paths.
What to do: Start node .next/standalone/server.js with SESSION_PASSWORD unset. Request /mandi (nothing to do with accounts or checkout) and /recipes.
Sample output (run for real against this harness):
$ PORT=3101 node .next/standalone/server.js # SESSION_PASSWORD unset
$ curl -s -o /dev/null -w "mandi: %{http_code}\n" http://localhost:3101/mandi
mandi: 500
$ curl -s -o /dev/null -w "recipes: %{http_code}\n" http://localhost:3101/recipes
recipes: 500
💡 Hint: proxy.ts's matcher (/status, /account/dashboard, /quickcart/checkout, /quickcart/admin, and their :path* variants) names nothing under /mandi or /recipes either — confirming section 5's point generalizes to any route in this harness, not just the two the README happened to show.
Exercise 3: Prove the divergence is about the file, not the data
Scenario: Section 4 showed a guestbook post landing in .next/standalone's copy, not the project's. Confirm the reverse also holds — a write made directly against the project's database is invisible to the standalone server, too.
What to do: With the standalone server running, add a row directly to app/mandi/guestbook/mandi-guestbook.sqlite using a scratch node -e script (not through any running server). Then request /mandi/guestbook from the standalone server and confirm the new row is absent.
Sample output (run for real against this harness):
$ node -e "... new Database('app/mandi/guestbook/mandi-guestbook.sqlite').prepare('INSERT INTO guestbook_entries (name, message) VALUES (?, ?)').run('Direct Writer', 'inserted straight into the project db') ..."
inserted directly into project db
$ curl -s http://localhost:3101/mandi/guestbook | grep -o 'Direct Writer' || echo "Direct Writer NOT present in standalone response"
Direct Writer NOT present in standalone response
$ node -e "... new Database('.next/standalone/app/mandi/guestbook/mandi-guestbook.sqlite').prepare('SELECT * FROM guestbook_entries').all() ..."
[]
💡 Hint: This is the same finding as section 4, from the other direction — the standalone server's db.ts module opened .next/standalone/app/mandi/guestbook/mandi-guestbook.sqlite once, at its own process start, and has no idea the project's separate file even exists, let alone that it changed. The two files are simply two different SQLite databases that happen to share a schema, not two views onto the same data.
Exercise 4: Watch onRequestError's context change shape for a different error source
Scenario: Section 6's probe was a Route Handler (context.routeType: "route"). Confirm the same hook reports a different routeType for an error thrown somewhere else — a form-bound Server Action.
What to do: Temporarily make addToCartAction (app/quickcart/actions.ts) throw unconditionally at the top (e.g. throw new Error("scratch Server Action error"), before anything else in the function runs). Start next dev, grab the real $ACTION_ID_... field from /quickcart/p1's rendered HTML (Part 12's pattern, same as this part's own section 4), and curl the same multipart POST the real "Add to cart" form would send. Read the logged context. Revert the change afterward.
Sample output (run for real against this harness):
$ curl -s -D - -X POST http://localhost:PORT/quickcart/p1 \
-F '$ACTION_ID_<real id from the page>=' -F 'productId=p1' -F 'quantity=1'
HTTP/1.1 500 Internal Server Error
[onRequestError] App Router render (undefined) POST /quickcart/p1 -> scratch Server Action error
💡 Hint: This is a genuinely surprising result worth sitting with: context.routeType reports "render" here, not "action" — even though the error came from a Server Action, not a page render in the usual sense. The installed type signature (routeType: 'render' | 'route' | 'action' | 'proxy') names "action" as a value, but this install classifies a form-bound action's failure under the page it was invoked from (/quickcart/p1's own render cycle) instead. Don't assume a documented union type's every value is reachable from every call site you'd expect — confirm it, the way this exercise just did, rather than filtering an observability dashboard by a routeType value that may never actually appear for your app's own action-invocation style.
Exercise 5: Try to reproduce onRequestError firing from proxy.ts itself — and honestly report what actually happens
Scenario: Section 6 and Exercise 4 covered a Route Handler ("route") and a form-bound Server Action ("render", not "action" — Exercise 4's finding). The documented type signature also lists "proxy". Try to trigger it.
What to do: Temporarily add an unconditional throw new Error("scratch proxy error") near the top of the proxy function in harness/proxy.ts (inside the exported function, before any of its existing logic). Start next dev and request a path the matcher actually covers (e.g. /status), then a path it doesn't (e.g. /mandi). Read the terminal output carefully for an [onRequestError] line. Revert the change and confirm /status works normally again afterward.
Sample output (run for real against this harness):
$ curl -s -o /dev/null -w "status (matched): %{http_code}\n" http://localhost:PORT/status
status (matched): 500
$ curl -s -o /dev/null -w "status (unmatched): %{http_code}\n" http://localhost:PORT/mandi
status (unmatched): 200
⨯ Error: scratch proxy error
at proxy (proxy.ts:18:9)
(no "[onRequestError]" line anywhere in the terminal output for this request)
💡 Hint: This is the honest result, not a mistake to fix: on this exact install, under next dev, an error thrown inside proxy.ts's own body produces a real 500 and Next's own default error overlay — but never reaches this harness's onRequestError hook at all, despite "proxy" being a documented value of context.routeType. The matcher-scoping itself still works correctly (the unmatched /mandi request stays a clean 200, confirming this is unrelated to section 5's module-evaluation finding). Whether this is a genuine gap in this specific Next.js version, a next dev-only limitation, or something next start/a real deployment platform handles differently was not resolved here — flagged exactly as TOOLING.md's honesty rule requires, rather than asserted either way.
Show the solutions for Part 18 (5 files)
solutions/ex01.md
# Solution to Exercise 1
```text
$ npm run build
$ PORT=3101 SESSION_PASSWORD=<real value from .env.local> node .next/standalone/server.js # no cp yet
$ curl -s http://localhost:3101/ -o /tmp/home.html
$ grep -o '_next/static/chunks/[^"]*\.js' /tmp/home.html | head -1
_next/static/chunks/1pcw6gskne7pf.js
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3101/_next/static/chunks/1pcw6gskne7pf.js
404
```
With both `cp` commands run **while the server kept running** (no restart yet):
```text
$ cp -r public .next/standalone/ && cp -r .next/static .next/standalone/.next/
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3101/_next/static/chunks/1pcw6gskne7pf.js
404
```
Still `404`, even though `ls .next/standalone/.next/static/chunks/1pcw6gskne7pf.js` confirms the file is genuinely present on disk at that point. Stopping and restarting the same process (same files, no rebuild):
```text
$ kill <pid>; PORT=3101 SESSION_PASSWORD=<same value> node .next/standalone/server.js
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3101/_next/static/chunks/1pcw6gskne7pf.js
200
```
The practical takeaway: run both `cp` commands **before** the first start of `server.js` in any deploy script — copying into an already-running process's folder is not enough to make it serve the new files.
solutions/ex02.md
# Solution to Exercise 2
```text
$ PORT=3101 node .next/standalone/server.js # SESSION_PASSWORD unset
$ curl -s -o /dev/null -w "mandi: %{http_code}\n" http://localhost:3101/mandi
mandi: 500
$ curl -s -o /dev/null -w "recipes: %{http_code}\n" http://localhost:3101/recipes
recipes: 500
```
Both fail, exactly like `/` and `/quickcart` did in the README's own section 5 — `proxy.ts`'s `matcher` names only `/status`, `/account/dashboard`, `/quickcart/checkout`, `/quickcart/admin`, and their `:path*` variants; `/mandi` and `/recipes` are nowhere in that list, and the terminal's own error (`SESSION_PASSWORD is not set`, stack frame ending at `.next/server/middleware.js`) is identical regardless of which unmatched path is requested. This confirms the finding generalizes: a load-bearing env var missing from a `proxy.ts` import chain breaks the **whole app**, not a matcher-shaped subset of it, because the module graph is evaluated before any per-request matcher decision is made.
solutions/ex03.md
# Solution to Exercise 3
With the standalone server running (section 2's setup), a direct, scratch write straight into the **project's** own database file, bypassing every running server:
```text
$ node -e "
const Database = require('better-sqlite3');
const db = new Database('app/mandi/guestbook/mandi-guestbook.sqlite');
db.prepare('INSERT INTO guestbook_entries (name, message) VALUES (?, ?)').run('Direct Writer', 'inserted straight into the project db');
"
inserted directly into project db
```
Requesting the guestbook page from the **standalone** server:
```text
$ curl -s http://localhost:3101/mandi/guestbook | grep -o 'Direct Writer' || echo "Direct Writer NOT present in standalone response"
Direct Writer NOT present in standalone response
```
Confirmed directly against the standalone copy's own data:
```text
$ node -e "
const Database = require('better-sqlite3');
const db = new Database('.next/standalone/app/mandi/guestbook/mandi-guestbook.sqlite');
console.log(db.prepare('SELECT * FROM guestbook_entries').all());
"
[]
```
This is the README's section 4 finding from the other direction: writing to the project's file never reaches the standalone server's own, separately-opened copy, exactly as writing through the standalone server never reached the project's file. They are two independent SQLite databases on disk that happen to share a schema (`db.ts`'s `CREATE TABLE IF NOT EXISTS` runs identically against either), not two views onto the same data — the clean, general version of the finding, not an artifact of which direction the write happened in.
solutions/ex04.md
# Solution to Exercise 4
`app/quickcart/actions.ts`, temporarily:
```ts
export async function addToCartAction(formData: FormData) {
throw new Error("scratch Server Action error");
const productId = String(formData.get("productId") ?? "");
// ...rest unchanged...
}
```
The real `$ACTION_ID_...` field, read from `/quickcart/p1`'s own rendered HTML:
```text
$ curl -s http://localhost:PORT/quickcart/p1 | grep -o '\$ACTION_ID_[a-f0-9]*'
$ACTION_ID_4037940f0571b5cae19b4115c23c97f5968015c3ba
```
The real multipart POST, Part 12's pattern, and the real server log:
```text
$ curl -s -D - -X POST http://localhost:PORT/quickcart/p1 \
-F '$ACTION_ID_4037940f0571b5cae19b4115c23c97f5968015c3ba=' \
-F 'productId=p1' -F 'quantity=1'
HTTP/1.1 500 Internal Server Error
```
```text
[onRequestError] App Router render (undefined) POST /quickcart/p1 -> scratch Server Action error
⨯ Error: scratch Server Action error
at addToCartAction (app/quickcart/actions.ts:15:9)
```
`context.routeType` is `"render"`, not `"action"` — a real, verified surprise against the documented union type (`'render' | 'route' | 'action' | 'proxy'`), which names `"action"` as a value without it necessarily appearing for every kind of action invocation. This install classifies a form-bound Server Action's failure under the page/route it was invoked from, not a separate `"action"` bucket. The change was reverted immediately after this check — `git diff harness/app/quickcart/actions.ts` showed no changes once restored.
solutions/ex05.md
# Solution to Exercise 5
`harness/proxy.ts`, temporarily:
```ts
export async function proxy(request: NextRequest) {
throw new Error("scratch proxy error");
const { pathname, searchParams } = request.nextUrl;
// ...rest unchanged...
}
```
```text
$ npm run dev -- -p 3102
$ curl -s -o /dev/null -w "status (matched): %{http_code}\n" http://localhost:3102/status
status (matched): 500
$ curl -s -o /dev/null -w "status (unmatched): %{http_code}\n" http://localhost:3102/mandi
status (unmatched): 200
```
Full terminal output for the matched (`/status`) request:
```text
⨯ Error: scratch proxy error
at proxy (proxy.ts:18:9)
16 |
17 | export async function proxy(request: NextRequest) {
> 18 | throw new Error("scratch proxy error");
| ^
19 | const { pathname, searchParams } = request.nextUrl;
```
No `[onRequestError]` line appears anywhere in the log for this request — checked by grepping the full captured log file for `onRequestError`, with zero matches.
**Honest result:** despite `"proxy"` being a documented value of `Instrumentation.onRequestError`'s `context.routeType`, this exact install (`next dev`, Next.js 16.4.6) never invoked the hook for an error thrown inside `proxy.ts`'s own body — the error still produced a real `500` and Next's own default dev error overlay, just without reaching this harness's observability hook at all. The `/mandi` unmatched-path check (a clean `200`) confirms the `matcher` itself is working correctly and this isn't a matcher-scoping bug — it's specifically about whether `onRequestError` fires for this error source. Whether `next start` or a real deployment adapter behaves differently was not checked — flagged as unverified, not asserted either way. `proxy.ts` was restored immediately after this check; `git diff harness/proxy.ts` showed no changes once reverted.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Assuming output: "standalone"'s traced SQLite file is this project's live database |
It's a build-time snapshot the file tracer happened to capture while exercising the server module — reproduced in section 4 by posting through a running standalone server and finding the write in .next/standalone's copy, not the project's own file |
Use a real shared/managed database for anything deployed standalone; don't rely on file tracing to carry live data |
Forgetting cp -r public .next/standalone/ and cp -r .next/static .next/standalone/.next/ before running node .next/standalone/server.js |
The docs state plainly server.js does not copy these by default (expecting a CDN); without them, static assets and fonts 404 |
Run both cp commands (section 2) after every next build, or wire them into a deploy script |
Assuming a route outside proxy.ts's matcher is unaffected by a crash inside proxy.ts's import graph |
Reproduced directly in section 5: / and /quickcart, neither matched by this harness's matcher, both returned 500 the moment SESSION_PASSWORD was missing, because the proxy bundle's module graph is evaluated before the matcher decides anything |
Treat every env var a proxy.ts import chain depends on as load-bearing for the whole app, not just the paths the matcher names |
Treating next start's output: "standalone" warning as a real failure |
Section 3 showed a real 200 and unchanged cache headers right next to the warning — next start still reads the ordinary .next/ output directly either way |
Read the warning as "this bundle is redundant here," not "this is broken" — use node .next/standalone/server.js for the actual minimal-deployment case the warning is pointing at |
Guarding a Node-only API in instrumentation.ts with an if (NEXT_RUNTIME === "nodejs") branch and expecting the Edge-compatibility build warning to disappear |
Reproduced directly in section 6: the guard around the usage did not stop the warning, because Turbopack's check is static, not branch-aware | Move the Node-only code into a separate file and load it with a dynamic import(), the installed docs' own named pattern |
| Assuming this course's own local verification proves multi-instance behavior (cache coordination, version skew, the Server Actions encryption key) | None of this course's capstones has ever run as more than one process — section 7 states these as documented facts, not verified ones | Treat section 7 as a reading list for when a real multi-instance deployment happens, not a tested claim |
Quick recap
output: "standalone"measurably shrinks what you'd need to ship (62 MB vs. a 549 MBnode_modulesin this harness) but requires two manualcpsteps for static assets and produces a file-tracer snapshot of any local database file, not a live link to it.next startandoutput: "standalone"aren't incompatible — the warning says the combination is redundant, and a real200with correct cache headers proved it still works.- A missing, load-bearing environment variable inside
proxy.ts's import graph breaks every route in production, not just the ones itsmatchernames — Next's production runtime evaluates that module graph before the matcher gets a say. instrumentation.ts'sregister()/onRequestError()hooks are real, verified locally, and genuinely useful without any external provider — console logging today, a one-line swap to a real provider'sfetchcall later.- Everything about actual multi-instance behavior (cache coordination, version skew, the Server Actions encryption key) and actual hosting platforms is documented from the installed guides only — this part never deployed anywhere, created an account, or ran more than one server process at a time, by explicit, stated scope.
Checklist
- I built with
output: "standalone", measured its real size againstnode_modules, and rannode .next/standalone/server.jssuccessfully after copyingpublic/and.next/staticby hand - I reproduced the SQLite build-time-snapshot finding myself: posted through the standalone server, then checked both database files directly and saw them diverge
- I reproduced the missing-
SESSION_PASSWORDfailure against the standalone server and confirmed it broke a route outsideproxy.ts's ownmatcher, not just the ones inside it - I ran
next startwithoutput: "standalone"set and can explain why the warning it prints is not the same as a real failure - I reproduced the
instrumentation.tsEdge-runtimeprocess.pidwarning myself and fixed it with the dynamic-import()split, confirming the warning is actually gone afterward - I can list, from memory, which claims in section 7 this part only documented — and why none of them could be honestly verified inside this course's scope