Docs

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.

TS
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 prefix defaults to /assets. Pass buildClient()'s assets as hashedFiles: those files get immutable for a year, and any other file gets cacheControl. A missing file under the prefix is a 404, never a rendered page.
  • Your own files. A second mount on public/ serves them at /, with fallthrough: true so a path it has no file for reaches your routes.
  • Files hashed before the build. The fonts loadGoogleFont writes into public/fonts/ are in no manifest, so the public/ 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) => boolean predicate instead, with assets as new Set(build.assets): (path) => assets.has(path) || HASHED_FONT.test(path). A global or sticky pattern in the array is used without that flag, so lastIndex never skips a match; a predicate runs as written, so keep the patterns it tests free of g and y.
TS
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:

TS
// 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.

TS
// 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.

TS
// 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. createWebApp checks the policy before everything it answers: use middleware, mounts, the API, prerendered pages and pages. A refused path gets a bare 404 with cache-control: no-store, or what refuse returns.
  • The build's files. buildAssets: true (the default) serves on that host every file the build emitted. Set it to false and list files in paths to serve only some.
  • With nifra build. Export hostPolicy from backend/framework.ts. The generated server entry passes it and buildAssets to createWebApp, and checks it before its own static files on Bun, Node and Deno, and before the Cloudflare worker's ASSETS fallback (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. static runs 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 dev serves the bundle and public/ 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.

TS
// 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:

TS
// 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.

TS
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:

TS
// 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 example nifra 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 when nifra.assurance.ts names this app as its source, the check skips a fetch into that prefix by itself. Without that, list the prefixes in nifra.check.json next to package.json:
TS
{
  "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 check reports 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:
TS
{
  "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.