Custom server (createWebApp)
The standard project layout gets its server entry from nifra build. An app that calls createWebApp from its own entry wires the same pieces by hand. Each one is an option or a single call.
A complete entry
Everything on this page in one file. The sections below explain each part. This file typechecks against the current packages.
import { ONE_DAY, serveStatic } from "@nifrajs/core/serve-static"
import { createCspPolicy, createWebApp } from "@nifrajs/web"
import type { Manifest, RenderAdapter } from "@nifrajs/web"
// From your build: the framework adapter, the route manifest, and what buildClient() returned.
declare const adapter: RenderAdapter
declare const manifest: Manifest
declare const build: {
readonly entry: string
readonly assets: readonly string[]
readonly routes: Readonly<Record<string, readonly string[]>>
readonly css?: readonly string[]
}
declare const errors: { capture(error: unknown, tags: Record<string, string>): void }
// buildClient({ outDir: "dist/assets" }) writes the chunks where their /assets/ URLs point.
const files = serveStatic([
{ dir: new URL("./dist/assets/", import.meta.url), hashedFiles: build.assets, cacheControl: ONE_DAY },
{
dir: new URL("./public/", import.meta.url),
prefix: "/",
immutable: false,
cacheControl: ONE_DAY,
fallthrough: true,
},
])
const csp = createCspPolicy({
header: ({ sources }) => `default-src 'self'; script-src 'self' ${sources}; object-src 'none'`,
})
export const app = createWebApp({
adapter,
manifest,
clientEntry: build.entry,
routePreload: build.routes,
styles: build.css ?? [],
csp,
server: { requestTimeoutMs: 15_000, gracefulSignals: { drainMs: 8_000 } },
onLoaderError: (error, { route }) => errors.capture(error, { route }),
})
app.listen(3000, { static: files })Static and hashed files
serveStatic serves directories under URL prefixes, with the same options on every runtime: import it from @nifrajs/core/serve-static on Bun, and from @nifrajs/node or @nifrajs/deno there. Pass it as static, which runs before every route. It answers GET and HEAD only, refuses paths that leave the directory or name a hidden file, sets the content type and nosniff, and handles range requests. A path no mount's prefix covers reaches your routes.
- Hashed build output. A mount's
prefixdefaults to/assets. PassbuildClient()'sassetsashashedFiles: those files getimmutablefor a year, and any other file getscacheControl. A missing file under the prefix is a404, never a rendered page. - Your own files. A second mount on
public/serves them at/, withfallthrough: trueso a path it has no file for reaches your routes. - Files hashed before the build. The fonts
loadGoogleFontwrites intopublic/fonts/are in no manifest, so thepublic/mount names them with an array of patterns, matched on the encoded URL path, as below. A mount that serves both the build and such files takes a(path) => booleanpredicate instead, withassetsasnew Set(build.assets):(path) => assets.has(path) || HASHED_FONT.test(path). A global or sticky pattern in the array is used without that flag, solastIndexnever skips a match; a predicate runs as written, so keep the patterns it tests free ofgandy.
import { ONE_DAY, serveStatic } from "@nifrajs/core/serve-static"
// The fonts loadGoogleFont wrote into public/fonts/ are content-hashed; the rest of public/ is not.
const HASHED_FONT = /^\/fonts\/[\w-]+-[0-9a-f]{16}\.woff2$/
export const publicFiles = serveStatic({
dir: new URL("./public/", import.meta.url),
prefix: "/",
hashedFiles: [HASHED_FONT],
cacheControl: ONE_DAY,
fallthrough: true,
})On Node and Deno, serve() takes the same mounts. On Node they run before the app builds a Web request, which keeps the direct request path for everything else:
// doc-check: skip - fragment: app and build are the createWebApp app and buildClient() output above.
import { serve, serveStatic } from "@nifrajs/node" // or "@nifrajs/deno"
await serve(app, {
port: 3000,
static: serveStatic({ dir: new URL("./dist/assets/", import.meta.url), hashedFiles: build.assets }),
gracefulSignals: { drainMs: 8_000 },
})A build script that calls buildServer itself passes it the manifest buildClient returned. The generated server-manifest then exports buildAssets (a Set of every file the build emitted, by request path: the bundle and the copied public/ files) and isBuildAsset(pathname), so a hand-written static handler or gate can allow exactly the files that exist.
// doc-check: skip - fragment: a build script; the routes and entry paths are your app's.
import { buildClient, buildServer } from "@nifrajs/web/build"
const client = await buildClient({ routesDir: "routes", outDir: "dist/assets", clientModule })
// One option for the whole client build: entry, stylesheets, per-route CSS, copy chunks, and the
// set of files it emitted. Forgetting `styles` used to ship unstyled pages; there is nothing to forget.
await buildServer({ routesDir: "routes", serverEntry: "server.ts", outDir: ".build", target: "bun", client })Hosts that serve part of the app
An app that also answers on domains other people point at it usually must not show all of itself there: such a domain should not render your sign-in page under its own certificate. createHostPolicy names, per host, the page routes it renders and the other paths it serves, and takes the build's own files by token, never by guessing their names. A gate that knows only page paths refuses the page's stylesheet and bundle, and the page answers 200 while rendering unstyled and never hydrating.
// doc-check: skip - fragment: adapter, manifest and build as above; ./server-manifest is generated by buildServer.
import { createHostPolicy, createWebApp } from "@nifrajs/web"
import { buildAssets } from "./server-manifest"
const ownHosts = new Set(["app.example.com", "localhost"])
// On every other host (a domain pointed at the app): the public pages, the API they call, and
// exactly the files the build emitted. Nothing else renders there, the sign-in page included.
export const hostPolicy = createHostPolicy({
rules: [{
hosts: (host) => !ownHosts.has(host),
pages: ["/", "/p/:id", "/share/*"],
paths: ["/api/public/*"],
}],
})
export const app = createWebApp({ adapter, manifest, clientEntry: build.entry, hostPolicy, buildAssets })- Order.
createWebAppchecks the policy before everything it answers:usemiddleware, mounts, the API, prerendered pages and pages. A refused path gets a bare404withcache-control: no-store, or whatrefusereturns. - The build's files.
buildAssets: true(the default) serves on that host every file the build emitted. Set it tofalseand list files inpathsto serve only some. - With
nifra build. ExporthostPolicyfrombackend/framework.ts. The generated server entry passes it andbuildAssetstocreateWebApp, and checks it before its own static files on Bun, Node and Deno, and before the Cloudflare worker'sASSETSfallback (the build then routes every file, the client bundle included, through the worker). Vercel serves files from its CDN before the function runs, so there the policy governs pages and the API only. - In your own server.
staticruns before the app, so a file would skip the policy. Give each mount the check the generated entries use:allow: (host, pathname) => hostPolicy.allows(host, pathname, buildAssets). A path it refuses reaches the app, which applies the policy and answers 404. - In development.
nifra devserves the bundle andpublic/ahead of the app, so only pages and the API are checked there. - Soft navigations. A client-side navigation fetches the page's data from the server, which applies the policy, so a refused page fails there as it would on a full load.
nifra smoke checks it end to end. For each entry in a fixture's hosts it renders the pages on that host, fetches every file they reference (scripts and their imports, stylesheets and their url()s, icons) on the same host and expects 200, then expects each refused path to answer 404.
// doc-check: skip - fragment: a nifra.smoke.ts fixture's hosts field.
hosts: [{ id: "partner", host: "docs.partner.test", pages: ["/", "/p/demo"], refused: ["/login"] }]A strict CSP on nifra's nonce
Pass createCspPolicy as csp and nifra writes the Content-Security-Policy header for each document. You do not stash a nonce or set the header yourself. Your header function receives sources: a hash for each constant inline script nifra writes, plus a nonce only when the document carries a request-specific script (a defer()ed value, or unsafeInlineScript in meta).
A document without a nonce gets the same header on every request, so it can still be cached by withISR or a CDN. A document with a nonce is sent private, no-store. The older nonce option puts a nonce on every document, so nothing is cacheable. createWebApp refuses csp and nonce together.
Middleware goes in use
createWebApp declares every page route, and the /* catch-all, before it returns. beforeHandle, afterHandle, around, derive, decorate and onError are copied into each route when the route is declared. One of those hooks added to the returned app would therefore reach no page. requestId() is a derive: added late, no page would see c.requestId. Outside production, adding one throws a FrameworkError with code HOOK_AFTER_PAGES that names the call site. Hooks added inside app.group(prefix, ...) are still allowed, because a group is its own scope.
Apply middleware in the use option instead. It runs before any page is declared, and ahead of mounts and the api mount, so an onRequest guard also covers a mounted auth handler:
// doc-check: skip - fragment: the use option of the createWebApp call above; @nifrajs/middleware is not installed in the docs sandbox.
import { requestId, securityHeaders } from "@nifrajs/middleware"
createWebApp({
// ...
use: (app) => {
app.use(securityHeaders())
app.use(requestId())
},
})onRequest and onResponse are read per request, so those two still work when added late. Putting everything in use means you never need to remember which hooks those are.
A plugin applied in use works at runtime but cannot add to the returned app's type. To get c.requestId typed on routes you declare afterwards, call app.use(requestId()) again on the returned app. Named plugins apply once.
Loader errors
When a loader or action throws and an _error boundary renders the page, the error is written to the server's logger, at the detail set by server.errorLogDetail. That is the same log line an unhandled 500 produces, and you do not need to configure anything for it. A soft-navigation data request that fails is logged the same way. A thrown Response, such as redirect(), is not an error and is not logged.
onLoaderError is for an error reporter. It sees every real throw with the request, params and route id before the boundary renders. If it throws, the error is ignored so rendering continues.
Graceful shutdown
On Bun, server: { gracefulSignals: { drainMs } } makes listen() handle SIGTERM and SIGINT. The server gives in-flight requests up to drainMs (default 10 000) to finish, then stops, closing any that are still running. On Bun, new connections can still arrive during that window, so the load balancer should stop routing to the instance first, as most platforms do before they send SIGTERM. Keep drainMs under your platform's kill grace period: docker stop waits 10 seconds. true uses the default. On Node and Deno, pass the same gracefulSignals: { drainMs } to serve() instead, as above.
When the platform sends SIGTERM without taking the instance out of rotation first, add delayMs. The stop then runs the app's onStopping hooks, keeps serving for delayMs, and only then drains. healthcheck() answers 503 stopping on /ready from the moment the stop begins, so the delay is the time a load balancer gets to see that and route elsewhere. Register your own app.onStopping(fn) to stop a poller or queue consumer at the same point; app.onStop(fn) still runs after the drain, on Bun, Node and Deno alike. delayMs + drainMs has to fit in the kill grace period.
To stop at the end of a scope instead of on a signal, hold the handle with await using. The handle listen() returns, the one serve() returns on Node and Deno, and the worker @nifrajs/jobs starts all stop when the scope ends, on a throw or an early return too. On Bun, disposal runs the app's graceful app.stop() with its default options, not Bun's raw stop. On Node and Deno it calls the stop() of the serve() handle, also with default options, which runs the same onStopping and onStop hooks and drains the same way; it does not call app.stop(), which would leave that listener open. If a shutdown is already under way, disposal waits for that one rather than starting another. A @nifrajs/cron scheduler is synchronous, so it takes using.
import { server } from "@nifrajs/core"
import { createScheduler } from "@nifrajs/cron"
import { createQueue } from "@nifrajs/jobs"
const app = server().get("/", () => "ok")
const queue = createQueue()
export async function runUntilDone(done: Promise<void>): Promise<void> {
await using running = app.listen(3000) // graceful stop() when the scope ends
await using worker = queue.start() // stops polling, waits for jobs in flight
using scheduler = createScheduler() // stop() when the scope ends
scheduler.start()
await done
console.log(running.port, worker.running)
}This needs a runtime and a TypeScript lib that know explicit resource management (esnext.disposable). Nifra's own declaration files reference that lib, so importing them is enough for the types.
Letting check and assure read the app
nifra check, assure, routes and the other commands that read the app import it, so everything the app does at module scope runs. A command that only reads what the app declares sets NIFRA_REFLECT to its own name first: check, routes, context, openapi, contracts, capabilities, manifest, doctor, diff, sync-manifest, and assure without --bundle, --strict, --hydration, --interact or --out. Commands that send the app requests, such as smoke, prove, levels and the assure bundle, leave it unset. Check it to skip work a read never needs:
// doc-check: skip - fragment: an app module's Redis client; ioredis is not installed in the docs sandbox.
import Redis from "ioredis"
// Unset when the app really runs; "check", "routes", "assure", ... while nifra only reads it.
export const redis = process.env.NIFRA_REFLECT ? undefined : new Redis(process.env.REDIS_URL!)- Environment validation. An app that validates its environment on import still needs values to pass it. Supply them with
--env-file, for examplenifra check --env-file .env.example. Variables already set in the shell win. - A process that will not exit. If something the app opened is still keeping the process alive 2 seconds after the command has answered, the command exits with its own result and says that the app kept it open.
nifra check for a custom entry
- Routes nifra cannot see. A mounted handler such as better-auth answers paths that are not in your backend, and no typed client covers them. Declare the mount opaque,
mounts: [{ path: "/api/auth", app: auth, opaque: "better-auth" }], and whennifra.assurance.tsnames this app as itssource, the check skips afetchinto that prefix by itself. Without that, list the prefixes innifra.check.jsonnext topackage.json:
{
"externalMounts": ["/api/auth"]
}- One call nifra cannot type. For a single call rather than a whole prefix, such as a static file, put
// nifra-expect NF-C002: <reason>on the line or in the comment block above it. The finding stays in the report as info, with your reason. A comment with no reason silences nothing. - Two repositories, one runtime. When a linked sibling repository brings its own install of nifra or React,
nifra checkreports the duplicates. A reinstall in this app cannot remove a copy that another project installed. Declare the packages single-copy and nifra loads this app's copy for every importer:
{
"name": "my-app",
"nifra": { "singleCopy": ["@nifrajs/*", "react", "react-dom"] }
}Packages duplicated the same way are reported as one finding with one combined singleCopy list. The preload this needs, and the version-skew case it cannot cover, are in Troubleshooting.