@hyperfrontend/ server§
HTTP kernel for Node.js services: a listener with graceful shutdown, a step pipeline, static file serving with compression and conditional requests, and ordered header rules.
What is @hyperfrontend/server?
@hyperfrontend/server is a small HTTP kernel for Node.js: helpers that start and stop a server, a pipeline of steps that each return a complete response, and a static file server built on that pipeline. It is the HTTP layer of the static server in @hyperfrontend/features, published on its own.
It is not a web framework. There is no router, no request body and no asynchronous middleware, and it loads no configuration file: you hand it a serving plan as an object. To serve a built micro-frontend from the command line, use hf serve from @hyperfrontend/features, which finds and resolves the plan for you.
Key Features
Listener helpers
Start a server and get the bound port back, with a refused port as a rejected promise
Graceful shutdown
One promise that settles on an interrupt or terminate signal, ready to await before closing
Step pipeline
A step answers a request or delegates inward and transforms the response that comes back
Static file serving
Content types, directory indexes, a redirect to the slashed directory URL, and 404 for dotfiles and symlinked paths
Compression
Brotli or gzip by negotiation for text responses, compressed once per file and encoding
Conditional requests
A weak entity tag on every file, and 304 when the client already holds it
Ordered header rules
Response headers by path prefix and suffix, a later rule overriding an earlier one per header
Framing policy as a field
A list of embedders expands into the header that says who may frame a page
Cross-origin isolation in one word
A declared isolation expands into the three headers that produce it
Header presets
Functions that write a content security policy, a permissions policy and cache rules for you
Policy without Node.js
The config shape, its validators and the presets sit in an entry that imports no built-in
No dependencies
The published package is self-contained; installing it adds nothing else
Why Use @hyperfrontend/server?
Headers a reviewer can read
What a deployment sends is a list of rules in a plain object: which paths, which headers, in which order. Who may frame a page, which browser features it may use and whether it is cross-origin isolated are one field each instead of headers spelled by hand. The validators report every problem of a config at once when the plan loads, not on the first request that matches a rule, and refuse a rule that would silently drop the framing policy.
A pipeline you can test without a port
A step is a function from a request value to a response value, and the file reads, the server factory and the log sink are all parameters. A spec runs the whole pipeline over an in-memory site.
Nothing else to install
The package has no dependencies. It serves a built site with compression, entity tags and the right content types on Node.js 18 or later.
Installation
npm install @hyperfrontend/server
Requires Node.js 18 or later.
Quick Start
Serve a directory that one other site may frame, with cross-origin isolation and two cache rules, until the process is stopped:
import { resolve } from 'node:path'
import { startStaticServer, waitForShutdown } from '@hyperfrontend/server'
import { expandHeaderPolicy, immutableAssets } from '@hyperfrontend/server/policy'
const server = await startStaticServer(
{
root: resolve('dist/site'),
port: 8080,
log: true,
headers: expandHeaderPolicy({
embedders: ["'self'", 'https://host.example'],
isolation: 'require-corp',
headers: [{ suffix: '.html', headers: { 'Cache-Control': 'no-cache' } }, immutableAssets('/assets/')],
}),
},
{ log: (line) => console.log(line) }
)
console.log(`Serving ${server.url}`)
await waitForShutdown()
await server.close()
The root is an absolute path, and port 0 lets the operating system choose one; read it back from the handle. The access log is written only when a log function is passed as well: log: true on its own prints nothing. expandHeaderPolicy turns the declared fields into rules placed ahead of the authored ones. It checks those fields and the rules the way the config validator does, and throws when a rule is malformed, a source would permit every origin, or a rule undoes the declared embedders.
A step placed in front of the built-ins sees every request first and every response last. What such a step answers by itself carries no header rule, since the rules are applied by the built-in steps:
import type { ServeStep } from '@hyperfrontend/server'
import { plainResponse, startStaticServer } from '@hyperfrontend/server'
const health: ServeStep = (request, context, next) => {
return request.url === '/healthz' ? plainResponse(200, 'ok') : next()
}
const plan = { root: process.cwd(), port: 0, log: false, headers: [] }
const server = await startStaticServer(plan, { steps: [health] })
API Overview
| Entry | What it is |
|---|---|
@hyperfrontend/server | The listener helpers, waitForShutdown, the step pipeline (runSteps, buildServeSteps), the static server (startStaticServer, createServeListener) and its path helpers |
/policy | The serve config as data: defineServeConfig, validateServeConfig and checkServeConfig, expandHeaderPolicy and applyHeaderRules, the header presets and the config types, with no Node.js built-in behind them |
createServeListener returns the request listener without starting anything, for a server you create yourself. createStaticHandler is a smaller handler that only confines the path, refuses symlinks and sets a content type, with no pipeline behind it. Every export, option and type is in the API reference.
Limitations
- Steps are synchronous and a file is read whole before it is answered. There is no streaming and there are no range requests, so it is not the server for very large files.
- The built-in pipeline answers GET and HEAD only, and a step never sees a request body.
- The plan arrives resolved: an absolute root, a concrete port and the header rules in their final order. Nothing here reads a config file or applies defaults.
- The only caching header set for you is the entity tag. A cache lifetime is a header rule you write.
- No security header is sent unless the plan carries it. A page with no embedders declared can be framed by any origin.
- No symlink below the root is followed, but a hard link is a file like any other and is served. A writer who can swap a directory for a link between the check and the read is outside what a path check can stop, so keep the served directory writable by the deployment alone.
- The server speaks plain HTTP. Terminate TLS in a proxy in front of it.
Compatibility
Runs on
- Node.js>=18.0.0supported
- Browserspartially supported
- Web Workerspartially supported
- Linuxsupported
- macOSsupported
- Windowssupported
Support is per entry point: the root entry is the HTTP kernel and is Node-only, and /policy imports no Node.js built-in, so it also runs in a browser or a web worker once a bundler includes it. The package publishes no browser bundle of its own.
Ships as
- ESMTree-shakeable
- CJSNode and older bundlers
Architecture Highlights§
- The root confines every path: a request path is decoded once and resolved under the root; a path that escapes answers 403, a malformed encoding 400. No symlink at or below the root is followed: a path that is one, or that passes through one, answers 404.
- A rule follows the file that is served: a rule bounded by a prefix or suffix is matched against the file's path as the file system stores it, so a request that reaches the file under another letter case or a Windows short name is sent the headers of that file.
- The pipeline owns the headers that describe the body: a header rule cannot override
Content-Length,Content-Encodingor the entity tag. - Every answer carries the plan's headers: the rules are folded over each response the built-in steps give, a 405 for a refused method included.
- One request cannot stop the server: a step that throws is answered with 500, which carries the rules too and is marked
Cache-Control: no-store.
The architecture guide covers the order of the built-in steps, how header rules fold and when a response is compressed.
API Reference§
Module Structure
2 modules · 59 total exports
HTTP kernel for Node.js services: a listener with graceful shutdown, a step pipeline, static file serving with compression and conditional requests, and ordered header rules.
ƒ Functions
Returns
numberExample
Reading the bound port after listen
server.listen(0, () => console.log(addressPort(server)))Accept-Encoding, with compressed bytes cached per file so a static deployment compresses each asset once per encoding. HEAD requests skip compression so their advertised
Content-Length stays the identity size, and a Cache-Control: no-transform set by a header rule is honored. Bodiless answers for compressible resources (HEAD, 304) still carry Vary: Accept-Encoding so caches keep encodings apart.Returns
ServeStepExample
Composing the step into a custom pipeline
const steps = [buildCompressionStep(), terminalStep]Every answer the built-ins give carries the header rules that match it: the method guard folds them over its own 405, and the header-rules step over everything the file step answers.
Header rules sit inside compression so a rule's headers shape what the compressor sees: a rule-set
Cache-Control: no-transform suppresses encoding and a rule-set Content-Type decides compressibility. Custom steps prepend to this chain, so a plugin sees every request first and every response last.Parameters
| Name | Type | Description |
|---|---|---|
§config | ResolvedServeConfig | The resolved serving plan. |
§deps | ServeStepDeps | Injectable file-system boundaries.(default: {}) |
Returns
ServeStep[ ]Example
Assembling the default pipeline
const steps = buildServeSteps(resolved, {})Returns
Promise< void>Example
Tearing a server down
await closeServer(server)root, rejecting any path that escapes the root via ... The root is normalised before the comparison, so a root spelled with a trailing slash or with forward slashes on Windows confines the same files as its canonical spelling. Leading slashes and backslashes are stripped from the request path first, so it is always resolved relative to the root.
Parameters
Returns
stringnull when the path escapes root.Example
Rejecting a traversal attempt
confineDecodedPath('/abs/dist', '/../secret') // nullContent-Type, falling back to octet-stream.Parameters
| Name | Type | Description |
|---|---|---|
§filePath | string | The path whose extension selects the MIME type. |
Returns
stringExample
Looking up a stylesheet's type
contentTypeFor('/abs/dist/app.css') // 'text/css; charset=utf-8'createServeListener( config: ResolvedServeConfig, deps: StaticServeDeps): ( req: IncomingMessage, res: ServerResponse) => void
Cache-Control: no-store. This is the replacement seam: anything that can call this listener (Node's
http.createServer, a test harness, or another runtime adapter) can host the pipeline unchanged.Parameters
| Name | Type | Description |
|---|---|---|
§config | ResolvedServeConfig | The resolved serving plan. |
§deps | StaticServeDeps | Optional file-system, logging, and pipeline overrides.(default: {}) |
Returns
( req: IncomingMessage, res: ServerResponse) => voidhttp.createServer.Example
Hosting the pipeline on a hand-made server
const server = createServer(createServeListener(resolved))createStaticHandler( root: string, deps: StaticHandlerDeps): ( req: IncomingMessage, res: ServerResponse) => void
Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The absolute directory files are served from. |
§deps | StaticHandlerDeps | Optional file-system overrides.(default: {}) |
Returns
( req: IncomingMessage, res: ServerResponse) => voidhttp.createServer.Example
Serving a compiled app directory
const server = createServer(createStaticHandler('/abs/dist'))decodeURIComponent throw inside a request handler.Parameters
| Name | Type | Description |
|---|---|---|
§path | string | The request path with the query string already stripped. |
Returns
stringnull when the encoding is malformed.Example
Rejecting a malformed encoding
decodeRequestPath('/%') // nullThe location is derived from the resolved path rather than the raw request, so it is always a single-slash path relative to this server's own root: a request that writes an authority into the URL (
//example.com/../host) is answered with the directory it actually resolved to, never with a location pointing off this origin.Parameters
Returns
stringExample
Redirecting a directory request
directoryLocation('/srv', '/srv/host', '/host?debug=1') // '/host/?debug=1'Parameters
Returns
stringundefined when absent.Example
Reading a content type set in any case
headerValue({ 'content-type': 'text/html' }, 'Content-Type') // 'text/html'Parameters
Returns
Promise< number>Example
Listening on an OS-assigned port
const port = await listen(server, 0)Accept-Encoding header into the preferred supported encoding. Preference is brotli, then gzip: the order every mainstream browser also ranks them in. A
* token stands in for both. Encodings disabled with q=0 are never chosen.Parameters
| Name | Type | Description |
|---|---|---|
§header | string | The raw Accept-Encoding value. |
Returns
"br" | "gzip"'br', 'gzip', or null when neither is acceptable.Example
Negotiating a browser's default header
negotiateEncoding('gzip, deflate, br') // 'br'Returns
StaticResponseExample
Building a 404
plainResponse(404, 'Not Found')/ and dropping any query string.Parameters
| Name | Type | Description |
|---|---|---|
§url | string | The raw request URL (req.url), which may be undefined. |
Returns
stringExample
Stripping a query string
requestPath('/app.js?v=2') // '/app.js'runSteps( steps: unknown, request: StaticRequest, context: ServeStepContext): StaticResponse
next(). A pipeline whose steps all delegate past the end answers 404, so a custom chain without a terminal step still returns a response.Parameters
| Name | Type | Description |
|---|---|---|
§steps | unknown | The ordered steps, outermost first. |
§request | StaticRequest | The request to answer. |
§context | ServeStepContext | The shared per-request context. |
Returns
StaticResponseExample
Running a request through a custom step and the built-ins
const response = runSteps([...customSteps, ...builtInSteps], request, { config })serveFile( root: string, urlPath: string, res: ServerResponse, deps: StaticHandlerDeps): void
root to the response, sending 403 on a traversal attempt and 404 when the file is missing. A URL ending in
/ serves that directory's index.html, so / and /host/ reach the pages a multi-page build emits as index.html and host/index.html. A directory URL written without the trailing slash (/host) answers 301 to the slashed form, keeping relative asset URLs on the page resolvable. No symbolic link at or below the root is followed: a file that is a link, or that sits below a linked directory, answers 404, and a directory whose index is reached through a link is never redirected to. The root itself may be a link.
Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The absolute directory files are served from. |
§urlPath | string | The request path (with or without a query string). |
§res | ServerResponse | The HTTP response to write. |
§deps | StaticHandlerDeps | Optional file-system overrides.(default: {}) |
Examples
Serving an app's `index.html`
serveFile('/abs/dist', '/', res)Serving a companion page from a multi-page build
serveFile('/abs/dist', '/host/', res) // sends /abs/dist/host/index.htmlstartStaticServer( config: ResolvedServeConfig, deps: StaticServeDeps): Promise< StaticServerHandle>
Parameters
| Name | Type | Description |
|---|---|---|
§config | ResolvedServeConfig | The resolved serving plan. |
§deps | StaticServeDeps | Optional server-creation, file-system, logging, and pipeline overrides.(default: {}) |
Returns
Promise< StaticServerHandle>Example
Serving a built site
const handle = await startStaticServer(resolved)
console.log(handle.url)
await handle.close()Used by long-running services to stay alive after startup and tear down gracefully when the user (or the process supervisor) stops them.
Returns
Promise< void>SIGINT or SIGTERM is received.Example
Stay alive until the target is stopped
await waitForShutdown()
await handle.close()◈ Interfaces
Properties
filePath?:stringAbsolute path of the file the terminal step resolved, recorded for path-matched header rules.Properties
readonly stat?:( filePath: string) => FileStatsReads the stats of a path without following a link in its last segment, or null when the path is unreadable; asked about a file and each directory between it and the root.readonly realPath?:( path: string) => stringLooks up the path the file system stores a path under, every link resolved and every name in the spelling its directory lists, or null when it cannot tell; asked about the root and a file about to be served, when a header rule is bounded by a prefix or suffix and when compressed bytes are not yet cached under the path as resolved.Properties
readonly isSymlink?:( path: string) => booleanReports whether a path is itself a symbolic link, without following it; asked about a file that exists and each directory between it and the root.Properties
Properties
Properties
readonly createServer?:( handler: ( req: IncomingMessage, res: ServerResponse) => void) => ServerCreates an HTTP server from a request handler.readonly steps?:unknownCustom steps prepended to the built-in pipeline; the first step sees every request first.readonly stat?:( filePath: string) => FileStatsReads the stats of a path without following a link in its last segment, or null when the path is unreadable; asked about a file and each directory between it and the root.readonly realPath?:( path: string) => stringLooks up the path the file system stores a path under, every link resolved and every name in the spelling its directory lists, or null when it cannot tell; asked about the root and a file about to be served, when a header rule is bounded by a prefix or suffix and when compressed bytes are not yet cached under the path as resolved.Properties
◆ Types
next() and transform what comes back: the innermost step serves the file, so next() always yields a complete response.type ServeStep = ( request: StaticRequest, context: ServeStepContext, next: ( ) => StaticResponse) => StaticResponseServing policy as data, free of Node.js built-ins: the serve-config shape and its validators, header policy presets, and the fold of ordered header rules.
ƒ Functions
applyHeaderRules( rules: unknown, path: string, headers: Readonly< Record< string, string>>): Record< string, string>
A rule applies when the path starts with its prefix and ends with its suffix, an absent bound matching everything. Each header of an applying rule replaces the header of the same name, compared without regard to case, so a later rule overrides an earlier one a header at a time and no header is sent under two spellings. A header keeps the position it first took. A rule's
Content-Length, Content-Encoding or ETag is skipped, since those describe the body.Parameters
Returns
Record< string, string>Example
Reading what a page and an asset are sent
const rules = [{ headers: { 'Cache-Control': 'no-cache' } }, { prefix: '/assets/', headers: { 'Cache-Control': 'immutable' } }]
applyHeaderRules(rules, '/index.html') // => { 'Cache-Control': 'no-cache' }
applyHeaderRules(rules, '/assets/app.js') // => { 'Cache-Control': 'immutable' }embedders field of a serve config: the origins allowed to frame what the server sends. An entry is
'self', 'none' as the only entry, or scheme://host with an optional leading *. label and an optional port, in lowercase ASCII with no path. Each entry is reported at most once, and no message repeats the entry it is about. A hole in the list is an entry that is no string.Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | The candidate list. |
Returns
unknownExample
Checking a list before it is published
checkEmbedders(["'self'", 'https://host.example']) // => []
checkEmbedders(['host.example']).map((issue) => issue.code) // => ['embedder-scheme-missing']permissionsPolicy field of a serve config: for each browser feature, the origins allowed to use it in the documents the server sends. A feature name is lowercase letters, digits and hyphens. Its allowlist is an array of
self, * as the only entry, or scheme://host origins; an empty array disables the feature. A name no browser knows is accepted, since browsers ignore it.Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | The candidate record. |
Returns
unknownExample
Checking a record before it is published
checkPermissionsPolicy({ camera: [], geolocation: ['self'] }) // => []
checkPermissionsPolicy({ camera: ["'self'"] }).map((issue) => issue.code) // => ['permissions-policy-keyword-quoted']Problems come in a fixed order:
root, port, host, log, isolation, headers and each rule; then any hole in the rule list and any header value Node would refuse to send; then embedders; then permissionsPolicy; then any rule that undoes the declared embedders, judged only when the rules and the embedders are themselves sound; then unknown fields, of the config and of each rule. $schema is the one extra field a config may carry. A value that is no object reports that alone.Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | The loaded config value. |
Returns
unknownExample
Listing what a tool should report about a config
checkServeConfig({ port: 0, embedders: ['host.example'] }).map((issue) => issue.message)
// => ['"port" must be an integer between 1 and 65535.', 'embedders[0] must start with a scheme and "://", as in https://host.example.']contentSecurityPolicy( options: ContentSecurityPolicyOptions, scope?: RuleScope): ServeHeaderRule
Content-Security-Policy: four default directives that load from the page's own origin, the authored directives, and frame-ancestors from the declared embedders, always last. An authored directive that names a default takes the default's position, and a new one follows the defaults in authored order.
X-Frame-Options is added when the embedders list is empty, 'none' or 'self' alone. The embedders are required: there is no safe guess for who may frame a page.Parameters
| Name | Type | Description |
|---|---|---|
§options | ContentSecurityPolicyOptions | The embedders and any directives beyond the defaults. |
§scope? | RuleScope | The paths the rule applies to; every path when omitted. |
Returns
ServeHeaderRuleExample
Allowing WebAssembly on the pages one host may frame
contentSecurityPolicy(
{ embedders: ['https://host.example'], directives: { 'script-src': ["'self'", "'wasm-unsafe-eval'"] } },
{ suffix: '.html' }
)crossOriginIsolation( coep: "require-corp" | "credentialless", scope?: RuleScope): ServeHeaderRule
Cross-Origin-Opener-Policy: same-origin, the chosen Cross-Origin-Embedder-Policy, and Cross-Origin-Resource-Policy: cross-origin, which keeps the origin embeddable by hosts elsewhere. It writes the headers a config's
isolation field expands into, and adds the scope the field cannot carry.Parameters
Returns
ServeHeaderRuleExample
Isolating one application of a site
crossOriginIsolation('credentialless', { prefix: '/app/' })hf-serve.config.* files type-checked authoring.Parameters
| Name | Type | Description |
|---|---|---|
§config | ServeConfig | The static-server configuration object. |
Returns
ServeConfigExample
Authoring a typed `hf-serve.config.ts`
export default defineServeConfig({ root: 'dist/site', headers: [{ headers: { 'X-Content-Type-Options': 'nosniff' } }] })Content-Security-Policy holding one frame-ancestors directive, followed by X-Frame-Options when the list is empty, 'none' or 'self' alone. The policy holds nothing else, so a later rule that sets the header replaces it whole; use
contentSecurityPolicy when the response needs other directives too.Parameters
Returns
ServeHeaderRuleExample
Letting one host frame every page
embedders(["'self'", 'https://host.example'])
// => { headers: { 'Content-Security-Policy': "frame-ancestors 'self' https://host.example" } }embedders, the rule for permissionsPolicy, the rule for isolation, then the authored rules. Each declared field becomes one rule that matches every path, and an empty permissions policy becomes none. The declared fields lead so that an authored rule still overrides any header they set. The one thing an authored rule may not do is undo the embedders: a rule that sets
Content-Security-Policy without a frame-ancestors directive, or an unbounded rule whose directive lists other sources, is refused. The four fields are checked the way a serve config's are, so a policy that never passed a validator is refused here with the same sentences and no rule is built from it. Any other field of the value is left unread.
Parameters
| Name | Type | Description |
|---|---|---|
§policy | HeaderPolicy | The policy fields of a serve config. |
Returns
unknownExample
Expanding the policy of a page one host may frame
expandHeaderPolicy({ embedders: ['https://host.example'], isolation: 'require-corp' })
// => [
// { headers: { 'Content-Security-Policy': 'frame-ancestors https://host.example' } },
// { headers: { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp', 'Cross-Origin-Resource-Policy': 'cross-origin' } },
// ]frame-ancestors directive from a list of embedders, in the order the list gives them. An empty list writes 'none'.Parameters
| Name | Type | Description |
|---|---|---|
§sources | unknown | The origins allowed to frame the response. |
Returns
stringExample
Writing the directive for a page two sites may frame
frameAncestors(["'self'", 'https://host.example']) // => "frame-ancestors 'self' https://host.example"
frameAncestors([]) // => "frame-ancestors 'none'"frame-ancestors source list of each policy in a Content-Security-Policy header value. A comma separates whole policies, and a browser enforces every one of them, so the result holds one list per policy that names the directive. The name is matched without regard to case, and the first occurrence in a policy wins, as it does in a browser. A value in which no policy names the directive restricts no embedder and reads as an empty result.
A directive holding any character other than ASCII whitespace and visible ASCII is read as absent, because a browser discards it whole: a no-break space beside the name or a host that is not in its punycode form leaves the response framable by any origin.
Parameters
| Name | Type | Description |
|---|---|---|
§policy | string | The header value. |
Returns
unknownExample
Reading who may frame a response
frameAncestorsOf("default-src 'self'; frame-ancestors 'self' https://host.example") // => [["'self'", 'https://host.example']]
frameAncestorsOf("default-src 'self'") // => []
frameAncestorsOf("frame-ancestors 'self' https://b\u00fccher.example") // => []Cache-Control: public, max-age=31536000, immutable. Use it for files whose name changes whenever their content does.Parameters
| Name | Type | Description |
|---|---|---|
§prefix | string | The path the files sit under, such as /assets/. |
Returns
ServeHeaderRuleExample
Caching a build's hashed assets
immutableAssets('/assets/')
// => { prefix: '/assets/', headers: { 'Cache-Control': 'public, max-age=31536000, immutable' } }Cross-Origin-Opener-Policy: same-origin and the chosen Cross-Origin-Embedder-Policy are what make the document cross-origin isolated; Cross-Origin-Resource-Policy: cross-origin keeps the origin embeddable by hosts elsewhere.Parameters
| Name | Type | Description |
|---|---|---|
§isolation | "require-corp" | "credentialless" | The declared COEP value, or undefined when none was declared. |
Returns
unknownExample
Expanding a declared isolation
isolationRules('require-corp')/ excludes nothing, and neither does no suffix or an empty one. A header rule is read by its bounds alone. A rule that only looks bounded replaces a header on the whole site, so it is judged as a rule for every path wherever one is.
Returns
booleantrue when neither bound excludes a path.Example
Telling a rule for the whole site from one for its pages
matchesEveryPath({ prefix: '/' }) // => true
matchesEveryPath({ suffix: '.html' }) // => falseX-Content-Type-Options: nosniff.Parameters
Returns
ServeHeaderRuleExample
Sending the header on every path
nosniff() // => { headers: { 'X-Content-Type-Options': 'nosniff' } }permissionsPolicy( features: Readonly< Record< string, unknown>>, scope?: RuleScope): ServeHeaderRule
Permissions-Policy header listing the features in the order the record gives them. An empty record builds a rule that sets no header.Parameters
Returns
ServeHeaderRuleExample
Disabling the camera and keeping geolocation for this origin
permissionsPolicy({ camera: [], geolocation: ['self'] })
// => { headers: { 'Permissions-Policy': 'camera=(), geolocation=(self)' } }, a scheme on its own such as https:, or a host that is . Letter case is ignored, since a browser reads a source without regard to it.Parameters
| Name | Type | Description |
|---|---|---|
§source | string | One source expression, as written in a policy. |
Returns
booleantrue when the expression names no particular host.Example
Telling an open source from a wildcard over one site
permitsEveryOrigin('https://*') // => true
permitsEveryOrigin('https://*.host.example') // => falseReferrer-Policy header.Parameters
| Name | Type | Description |
|---|---|---|
§value | ReferrerPolicyValue | The policy; the origin alone on a cross-origin request when omitted.(default: 'strict-origin-when-cross-origin') |
§scope? | RuleScope | The paths the rule applies to; every path when omitted. |
Returns
ServeHeaderRuleExample
Sending no referrer from a private area
referrerPolicy('no-referrer', { prefix: '/private/' })
// => { prefix: '/private/', headers: { 'Referrer-Policy': 'no-referrer' } }Strict-Transport-Security header. The rule takes no scope, because a browser applies the header to the whole host whichever response carried it. Send it only from a server reached over HTTPS; a browser ignores it on plain HTTP.
Parameters
| Name | Type | Description |
|---|---|---|
§options | StrictTransportSecurityOptions | The lifetime, and whether subdomains and preloading are included. |
Returns
ServeHeaderRuleExample
Keeping a host and its subdomains on HTTPS for two years
strictTransportSecurity({ maxAge: 63072000, includeSubDomains: true, preload: true })
// => { headers: { 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload' } }prefix/suffix strings, a headers record of values Node can send, and no other field.Parameters
Returns
ServeHeaderRuleExample
Validating a single header rule
const rule = validateHeaderRule({ suffix: '.html', headers: { 'Cache-Control': 'no-cache' } }, 0, '/p/hf-serve.config.json')Parameters
Returns
ServeConfigExample
Validating a loaded serve config
const config = validateServeConfig({ root: 'dist/site' }, '/p/hf-serve.config.json')◈ Interfaces
Properties
readonly embedders:unknownThe origins allowed to frame the response, written last as the frame-ancestors directive; an empty list allows none.Properties
readonly path:stringWhere the problem sits in the config, such as embedders[2]; empty when the config itself is at fault.hf-serve.config.*: concrete root, listen address, and header rules.Properties
readonly sourcePath?:stringAbsolute path of the config file that was loaded, absent when serving with pure defaults.prefix (when given) and ends with suffix (when given); a scope with neither, like no scope at all, matches every path.Properties
hf-serve.config.* file.Properties
isolation?:"require-corp" | "credentialless"Cross-origin isolation applied to every response, expanded into Cross-Origin-Opener-Policy: same-origin, the matching Cross-Origin-Embedder-Policy, and Cross-Origin-Resource-Policy: cross-origin. Declaring it here rather than spelling the headers by hand keeps the intent legible and reviewable. The expansion is placed before the
headers rules, so an explicit rule still overrides any of the three. An isolated origin severs the opener of any window opened onto it unless that opener is both same-origin and itself isolated, so a page served this way keeps a working
window.opener only when a same-origin isolated page opens it.embedders?:string[ ]The origins allowed to frame every response, expanded into a Content-Security-Policy holding one frame-ancestors directive. An empty list allows none. X-Frame-Options is sent beside it when the list is empty, 'none' or 'self' alone. The expansion is placed ahead of every other rule, so a later rule may scope a different list to a prefix or suffix. A rule that sets
Content-Security-Policy must carry a frame-ancestors directive of its own, since the header is replaced whole; a rule that matches every path must list exactly the sources declared here. A source is refused when it would permit every origin (
, a scheme on its own, a host), carries a path, lacks a scheme, or is not lowercase ASCII. An IPv4 literal is accepted, though browsers differ on whether it ever matches.permissionsPolicy?:Record< string, string[ ]>The browser features the served documents may use, expanded into one Permissions-Policy header. Each key is a feature name and each value the origins allowed to use it: [] disables the feature, ['self'] keeps it for this origin, ['*'] allows every origin, and scheme://host entries name others. This restricts what a document can do whatever its embedder delegates; it is not the list of features a document asks its embedder for. The expansion is placed after the one for
embedders and ahead of the one for isolation.log?:booleanWhether each request is access-logged: one line per request, written to the log sink the server is given and nowhere when it is given none.A rule matches when the path starts with
prefix (when given) and ends with suffix (when given); a rule with neither matches everything. Rules are applied in order and later rules override earlier ones one header at a time.Properties
◆ Types
frame-ancestors source: 'self', 'none' as the only entry of its list, or scheme://host with an optional leading *. label and an optional port, in lowercase ASCII with no path.type EmbedderSource = stringtype HeaderPolicy = Pick< ServeConfig, "embedders" | "permissionsPolicy" | "isolation" | "headers">type PolicyIssueCode = "config-not-object" | "root-invalid" | "port-invalid" | "host-invalid" | "log-invalid" | "isolation-invalid" | "headers-not-array" | "rule-not-object" | "rule-prefix-invalid" | "rule-suffix-invalid" | "rule-headers-not-object" | "header-name-invalid" | "header-value-not-string" | "header-value-control-character" | "header-value-not-latin1" | "embedders-not-array" | "embedder-not-string" | "embedder-empty" | "embedder-control-character" | "embedder-separator" | "embedder-whitespace" | "embedder-not-ascii" | "embedder-not-lowercase" | "embedder-none-not-alone" | "embedder-keyword-unquoted" | "embedder-keyword-unknown" | "embedder-permits-every-origin" | "embedder-scheme-missing" | "embedder-has-path" | "embedder-port-invalid" | "embedder-wildcard-too-broad" | "embedder-malformed" | "embedders-dropped-by-rule" | "embedders-contradicted-by-rule" | "permissions-policy-not-object" | "permissions-policy-name-invalid" | "permissions-policy-allowlist-not-array" | "permissions-policy-entry-not-string" | "permissions-policy-wildcard-not-alone" | "permissions-policy-keyword-quoted" | "permissions-policy-origin-invalid" | "unknown-field" | "rule-unknown-field"Referrer-Policy header takes.type ReferrerPolicyValue = "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url"Related reading§
- Architecture
Architecture
How @hyperfrontend/server is put together, and why.
- Getting started
Getting Started
Set HyperFrontend up and embed a first feature.
- Architecture
Architecture Guide
How the packages fit together.
No guides cover @hyperfrontend/server yet.Request one