bini-server 2.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,8 +5,8 @@
5
5
  [![bundle size](https://img.shields.io/bundlephobia/min/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://bundlephobia.com/package/bini-server)
6
6
  [![downloads](https://img.shields.io/npm/dt/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
7
7
 
8
- **Production server for Bini.js apps.**
9
- Serves the output of your build from `dist/`: static files, pre-rendered pages, and the compiled API bundle at `dist/api/index.mjs`. It imports only Node.js built-in modules and [bini-env](https://www.npmjs.com/package/bini-env) (for `.env` loading).
8
+ Production server for Bini.js apps.
9
+ It serves the output of your build from `dist/`: static files, pre-rendered pages, the SPA shell, and the compiled API bundle at `dist/api/index.mjs`. Besides Node.js built-in modules, it imports [bini-env](https://www.npmjs.com/package/bini-env) (for `.env` loading) and the `toApiPath` helper from `bini-router/runtime`, so API paths are matched by the same rules as in development.
10
10
 
11
11
  ---
12
12
 
@@ -37,34 +37,36 @@ Serves the output of your build from `dist/`: static files, pre-rendered pages,
37
37
 
38
38
  - **Static file serving.** Streams files from `dist/` with MIME types, an `ETag`, and `Cache-Control` headers.
39
39
  - **API routes.** Forwards `<base>/api` and `<base>/api/...` requests to the `fetch` export of `dist/api/index.mjs`.
40
- - **Route-aware fallbacks.** Pre-rendered pages first, then shell pages for bracketed dynamic-route folders, then `404.html`, then `index.html`.
41
- - **ETag support.** Responds `304 Not Modified` when `If-None-Match` equals the file's ETag.
42
- - **Sub-path deployments.** Serve the app under a `BASE` path.
40
+ - **Standard page fallbacks.** The same order as `vite preview` and a typical static host: a real file, then a pre-rendered page, then the SPA shell `200.html` (status 200), then `404.html` (status 404), then a plain SPA `index.html`.
41
+ - **ETag support.** Responds `304 Not Modified` when `If-None-Match` matches the file's ETag.
42
+ - **Sub-path deployments.** Serve the app under a base path with `BINI_BASE`.
43
+ - **Optional compression.** Brotli and gzip for text files, enabled with `BINI_COMPRESS`.
43
44
 
44
45
  ### Security and Reliability
45
46
 
46
47
  - **Body limits.** Configurable request body size limit for API requests (default 10 MB).
47
48
  - **Timeouts.** Configurable body read and handler timeouts (default 30 s each).
48
- - **Path traversal protection.** Paths containing a `..` segment or a null byte are not served, and `dist/api/` is never served as static files.
49
+ - **Path safety.** Paths with a `..` segment, a backslash, or a null byte are rejected, and `dist/api/` and dotfolders such as `.bini` are never served.
49
50
  - **Error hiding in production.** With `NODE_ENV=production`, `500` responses contain only `Internal server error`.
50
- - **Port auto-increment.** Starts at `PORT` (default `3000`) and tries the next port while one is busy, up to 99 higher. Each busy port is logged.
51
+ - **Proxy-aware URLs.** With `BINI_TRUST_PROXY`, the API `Request` URL uses `X-Forwarded-Proto` and `X-Forwarded-Host`.
52
+ - **Health check.** `GET /__health` returns `ok`.
51
53
 
52
54
  ### Operations
53
55
 
54
56
  - **Env file loading.** Environment files are loaded through bini-env at startup, and the banner lists the files bini-env reports.
55
57
  - **Interactive shortcuts.** `h` for help, `o` to open the browser, `q` to quit (only when stdin is a terminal).
56
- - **Graceful shutdown.** Handles `SIGTERM` and `SIGINT`, with a 10 second fallback that exits with code 1.
57
- - **Flexible config.** Supports `BINI_*`, `VITE_*`, or unprefixed environment variables.
58
+ - **Graceful shutdown.** Handles `SIGTERM` and `SIGINT`, with a 10 second fallback.
59
+ - **Flexible config.** Most settings accept `BINI_*`, `VITE_*`, or unprefixed environment variables.
58
60
 
59
61
  ---
60
62
 
61
63
  ## Requirements
62
64
 
63
- - Node.js (the server uses the global `Request` and `Response` classes, `Headers#getSetCookie`, and `Readable.fromWeb`)
65
+ - A recent Node.js. The server uses the global `Request` and `Response` classes, `Readable.fromWeb`, and `server.closeAllConnections()`.
64
66
  - A finished build in `dist/` (relative to the working directory):
65
67
  - `dist/` (required; the server exits with code 1 if it is missing)
66
68
  - `dist/api/index.mjs` (the compiled API bundle; it must export a function named `fetch`)
67
- - Pre-rendered pages, `404.html`, and shell pages (optional)
69
+ - Pre-rendered pages, `200.html`, `404.html`, and `index.html` (whichever your build produces)
68
70
 
69
71
  ---
70
72
 
@@ -112,9 +114,10 @@ npm start # Serve in production
112
114
 
113
115
  - `(production)` is always printed.
114
116
  - `Environments` lists the env files reported by bini-env, relative to the working directory. It is omitted when there are none.
115
- - `Local` and `Network` show the port that was actually bound. They do not include `BASE`.
116
- - `Network` is the first private IPv4 address (`10.x.x.x`, `172.16-31.x.x`, `192.168.x.x`) of a non-internal interface. If there is none, it falls back to the first other non-internal IPv4 address (link-local `169.254.x.x` addresses are skipped). Interfaces whose names contain any of `docker`, `veth`, `br-`, `lo`, `loopback`, `vmnet`, `vbox`, `utun`, `tun`, or `tap` (case-insensitive) are ignored. The line is omitted when no address is found.
117
- - `Base` appears as an extra line when `BASE` is set.
117
+ - `Local` and `Network` show the port that was actually bound and include the base path when one is set (for example `http://localhost:3000/app/`).
118
+ - `Local` uses `localhost` when the server listens on `0.0.0.0`, `::`, or a loopback address, and the configured host otherwise.
119
+ - `Network` appears only when the server listens on `0.0.0.0` or `::`. It is the first private IPv4 address (`10.x.x.x`, `172.16-31.x.x`, `192.168.x.x`) of a non-internal interface. If there is none, it falls back to the first other non-internal IPv4 address (link-local `169.254.x.x` addresses are skipped). Interfaces whose names start with `veth`, `br-`, `utun`, `tun`, or `tap`, or contain `docker`, `vmnet`, or `vbox` (case-insensitive), are ignored. The line is omitted when no address is found.
120
+ - `Base` appears as an extra line when a base path is set.
118
121
 
119
122
  ### Programmatic start
120
123
 
@@ -129,13 +132,13 @@ await start()
129
132
  ### What `start()` does
130
133
 
131
134
  1. Loads env files with bini-env (mode is `NODE_ENV`, or `production` when it is not set), then re-reads the configuration.
132
- 2. Prints an error and exits with code 1 when the `dist` directory does not exist.
133
- 3. Scans `dist` once for shell pages.
134
- 4. Finds a free port, starting at `PORT` (see [Port selection](#port-selection)).
135
- 5. Creates the HTTP server, starts the keyboard shortcuts (if stdin is a terminal), listens on `0.0.0.0`, and prints the banner once listening.
136
- 6. Registers `SIGTERM` and `SIGINT` handlers.
135
+ 2. Prints a warning if the base path came from the unprefixed `BASE` variable (see [Environment Variables](#environment-variables)).
136
+ 3. Prints an error and exits with code 1 when the `dist` directory does not exist.
137
+ 4. Chooses the port (see [Port selection](#port-selection)).
138
+ 5. Creates the HTTP server, starts the keyboard shortcuts (if stdin is a terminal), listens, and prints the banner once listening.
139
+ 6. Registers `SIGTERM`, `SIGINT`, `unhandledRejection`, and `uncaughtException` handlers.
137
140
 
138
- `dist/api/index.mjs` is **not** loaded at startup. It is loaded on the first API request (see [API Routes](#api-routes)).
141
+ `dist/api/index.mjs` is not loaded at startup. It is loaded on the first API request (see [API Routes](#api-routes)).
139
142
 
140
143
  ---
141
144
 
@@ -161,7 +164,7 @@ At startup, bini-server calls bini-env's `loadEnvFiles` for the working director
161
164
 
162
165
  ### Server Configuration
163
166
 
164
- All settings support **three naming conventions:**
167
+ These settings support three naming conventions:
165
168
 
166
169
  | Convention | Example | Priority |
167
170
  | --- | --- | --- |
@@ -171,26 +174,37 @@ All settings support **three naming conventions:**
171
174
 
172
175
  | Variable | Default | Description |
173
176
  | --- | --- | --- |
174
- | `PORT` | `3000` | Port to start from. If it is in use, the next free port is used (see [Port selection](#port-selection)) |
177
+ | `PORT` | `3000` | Port to listen on (see [Port selection](#port-selection)) |
175
178
  | `DIST_DIR` | `dist` | Build output folder, relative to the working directory |
176
- | `BASE` | *(empty)* | Sub-path the app is served under. `''`, `/`, `.`, and `./` mean no base; any other value is normalized to a leading slash with no trailing slash (`app/` becomes `/app`) |
177
179
  | `BODY_TIMEOUT_SECS` | `30` | Max seconds to read an API request body |
178
180
  | `HANDLER_TIMEOUT_SECS` | `30` | Max seconds for the API handler to respond |
179
181
  | `BODY_SIZE_LIMIT` | `10485760` | Max API request body size in bytes (10 MB) |
180
182
 
181
- Numeric values are parsed with `parseInt`; a value that cannot be parsed as an integer falls back to the default. Setting a limit or timeout to `0` does **not** disable it: a body limit of `0` rejects any non-empty request body.
183
+ Numeric values are parsed with `parseInt`; a value that cannot be parsed as an integer falls back to the default. Setting a limit or timeout to `0` does not disable it: a body limit of `0` rejects any non-empty request body.
184
+
185
+ These settings are read in a fixed form:
186
+
187
+ | Variable | Default | Description |
188
+ | --- | --- | --- |
189
+ | `BINI_BASE` (or `VITE_BASE`) | *(empty)* | Sub-path the app is served under. `''`, `/`, `.`, and `./` mean no base; any other value is normalized to a leading slash with no trailing slash (`app/` becomes `/app`). The unprefixed `BASE` is still read as a fallback, with a warning, because other tools also set it |
190
+ | `BINI_HOST` | `0.0.0.0` | Address to listen on. Only the `BINI_` name is read, because bare names like `HOST` are set by other tools |
191
+ | `BINI_TRUST_PROXY` | off | Trust `X-Forwarded-Proto` and `X-Forwarded-Host` when building the API request URL |
192
+ | `BINI_COMPRESS` | off | Compress text responses with Brotli or gzip |
193
+
194
+ `BINI_TRUST_PROXY` and `BINI_COMPRESS` are on when set to `1`, `true`, `yes`, or `on` (case-insensitive).
182
195
 
183
196
  The server also reads `NODE_ENV`. Only when it is exactly `production` do `500` responses hide the underlying error message; otherwise the message is included.
184
197
 
185
198
  ### Port selection
186
199
 
187
- The server checks `PORT`, then each following port, until it finds one that is free on `0.0.0.0`. It logs one line for every busy port it skips:
200
+ - **`PORT` is set** (in any of the three forms): the server uses exactly that port. A value that is not an integer from 1 to 65535 stops the server with `invalid port`, and a port that is already in use stops it with `port <n> is already in use on <host>`. Both exit with code 1.
201
+ - **`PORT` is not set:** the server starts at `3000` and tries the next port while one is busy. It logs one line for every busy port it skips:
188
202
 
189
203
  ```text
190
204
  Port 3000 is in use, trying another one...
191
205
  ```
192
206
 
193
- The banner shows the port that was actually used. The search covers 100 ports (`PORT` through `PORT + 99`); if none is free, `start()` rejects with `No free port found in range <start>–<end>`.
207
+ The search covers 100 ports (`3000` through `3099`) on the configured host; if none is free, `start()` rejects with `No free port found in range <start>–<end>`. The banner shows the port that was actually used.
194
208
 
195
209
  ### Examples
196
210
 
@@ -200,6 +214,9 @@ PORT=3001 bini-server
200
214
 
201
215
  # With the BINI prefix (takes precedence over PORT)
202
216
  BINI_PORT=3002 bini-server
217
+
218
+ # Only reachable from this machine
219
+ BINI_HOST=127.0.0.1 bini-server
203
220
  ```
204
221
 
205
222
  ---
@@ -212,7 +229,8 @@ bini-server serves whatever is in `dist/` (or `DIST_DIR`). It does not read your
212
229
  dist/
213
230
  ├── index.html
214
231
  ├── about/index.html # Pre-rendered page
215
- ├── blog/[slug]/index.html # Shell page for a dynamic route
232
+ ├── about.html # Same page, file form
233
+ ├── 200.html # SPA shell (bini-ssg), used for every other page URL
216
234
  ├── 404.html
217
235
  ├── assets/
218
236
  └── api/
@@ -223,7 +241,7 @@ dist/
223
241
 
224
242
  ## API Routes
225
243
 
226
- Requests to `<base>/api` and `<base>/api/...` are passed to the `fetch` export of `dist/api/index.mjs`. The bundle is imported once, lazily, when the first API request arrives, and the result is reused for all later requests.
244
+ Requests to `<base>/api` and `<base>/api/...` are passed to the `fetch` export of `dist/api/index.mjs`. The bundle is imported once, lazily, when the first API request arrives, and the result is reused for all later requests. API requests are handled before the method check, so every HTTP method reaches the bundle.
227
245
 
228
246
  ### What the bundle receives
229
247
 
@@ -231,9 +249,9 @@ Requests to `<base>/api` and `<base>/api/...` are passed to the `fetch` export o
231
249
  fetch(request: Request, env: NodeJS.ProcessEnv, ctx: { waitUntil(p: Promise<unknown>): void })
232
250
  ```
233
251
 
234
- - **`request`:** a standard `Request` whose URL is `http://<host header><original request URL>` (the host defaults to `localhost` when there is no `Host` header). The URL keeps the original path, including `BASE` and `/api`. Header arrays are joined with `,` (the `cookie` header with `;`). The body is read for every method except `GET` and `HEAD`.
235
- - **`env`:** `process.env`.
236
- - **`ctx.waitUntil`:** accepts a promise and swallows its rejection; the server does not wait for it.
252
+ - `request`: a standard `Request` whose URL is `<proto>://<host><original request URL>`. The protocol is `http` and the host is the `Host` header (`localhost` when there is none). With `BINI_TRUST_PROXY`, the first value of `X-Forwarded-Proto` (`http` or `https`) and `X-Forwarded-Host` (letters, digits, `.`, `-`, `:`, `[`, `]` only) are used instead. The URL keeps the original path, including the base and `/api`. Header arrays are joined with `,` (the `cookie` header with `;`). The body is read for every method except `GET` and `HEAD`.
253
+ - `env`: `process.env`.
254
+ - `ctx.waitUntil`: accepts a promise and swallows its rejection; the server does not wait for it.
237
255
 
238
256
  The response status and headers (including every `Set-Cookie`) are copied, and the body is streamed to the client. `HEAD` requests receive headers only.
239
257
 
@@ -243,16 +261,21 @@ bini-server does not add CORS headers or answer preflight requests. Any CORS han
243
261
 
244
262
  ### Base path
245
263
 
246
- When `BASE` is set, only requests under it are treated as API requests (`<base>/api/...`). The `Request` passed to the bundle keeps the full original URL, including the base.
264
+ When a base path is set, only requests under it are treated as API requests (`<base>/api/...`). The `Request` passed to the bundle keeps the full original URL, including the base.
247
265
 
248
266
  ### Request limits
249
267
 
250
- `BODY_SIZE_LIMIT` and `BODY_TIMEOUT_SECS` apply while the body is read, and `HANDLER_TIMEOUT_SECS` applies while waiting for the handler. The handler is not cancelled when the timeout fires.
268
+ `BODY_SIZE_LIMIT` and `BODY_TIMEOUT_SECS` apply while the body is read, and `HANDLER_TIMEOUT_SECS` applies while waiting for the handler. The handler is not cancelled when the timeout fires. A request whose `Content-Length` is already above the limit is rejected with `413` before the body is read.
251
269
 
252
270
  ### When the bundle is missing or broken
253
271
 
254
- - **`dist/api/index.mjs` does not exist:** on the first API request the server prints a `[WARN] failed to load handler for /api:` message, and every API request returns `503` with `{"error":"No API routes compiled"}`.
255
- - **The file exists but fails to import, or does not export a `fetch` function:** every API request returns `500` with `{"error":"API failed to load"}`.
272
+ If `dist/api/index.mjs` does not exist, fails to import, or does not export a `fetch` function, the server prints a `[WARN] failed to load handler for <path>:` message with the underlying error, and the request returns `503` with a body like this:
273
+
274
+ ```json
275
+ { "error": "failed to load handler", "path": "/api/hello", "detail": "<error message>" }
276
+ ```
277
+
278
+ The load is attempted again on the next API request, so a bundle that appears later (or is fixed) is picked up without a restart.
256
279
 
257
280
  ---
258
281
 
@@ -260,85 +283,91 @@ When `BASE` is set, only requests under it are treated as API requests (`<base>/
260
283
 
261
284
  ### Lookup order
262
285
 
263
- For a path **with** a file extension (as determined by `path.extname`), the server looks for that file under `dist/`. Anything under `dist/api/` is never served. If the file does not exist, the response is a plain-text `404 Not found`.
264
-
265
- For a path **without** an extension, the server uses the first of these that applies:
286
+ A request is served from `dist/` in this order. The first step that applies wins:
266
287
 
267
288
  | Order | Looks for | Status |
268
289
  | --- | --- | --- |
269
- | 1 | `dist/<path>/index.html` (pre-rendered page) | 200 |
270
- | 2 | The `index.html` of a matching shell page | 200 |
271
- | 3 | `dist/404.html` | 404 |
272
- | 4 | `dist/index.html` | 200 |
273
- | 5 | Nothing found (plain-text `Not found`) | 404 |
290
+ | 1 | The file itself, or `<path>/index.html` when the path is a folder (a pre-rendered page) | 200 |
291
+ | 2 | `<path>.html`, for paths without an extension (the file form of a pre-rendered page) | 200 |
292
+ | 3 | Nothing, when the path ends in a known asset extension (`.js`, `.css`, `.png`, ...): plain-text `Not found` | 404 |
293
+ | 4 | `dist/200.html`, the SPA shell. Your client router renders the matching page or its not-found page | 200 |
294
+ | 5 | `dist/404.html`, when there is no `200.html` | 404 |
295
+ | 6 | `dist/index.html`, for a plain SPA build without `bini-ssg` | 200 |
296
+ | 7 | Nothing found: plain-text `Not found` | 404 |
274
297
 
275
- When `BASE` is set, only paths under it are served; other paths get the plain-text `404 Not found`.
298
+ Known asset extensions: `.js`, `.mjs`, `.css`, `.map`, `.json`, `.txt`, `.xml`, `.webmanifest`, `.png`, `.jpg`, `.jpeg`, `.gif`, `.svg`, `.ico`, `.webp`, `.avif`, `.woff`, `.woff2`, `.ttf`, `.otf`, `.eot`, `.pdf`, `.wasm`, `.mp4`, `.webm`, `.mp3`. Any other dotted path, such as `/blog/v1.2`, is treated as a page URL.
276
299
 
277
- ### Shell pages
300
+ This means a dynamic route that was not pre-rendered (for example a `/blog/<slug>` that is not in your static params) gets the `200.html` shell and is rendered by the client.
278
301
 
279
- At startup the server scans `dist` once for folders whose names are wrapped in square brackets and that contain an `index.html`, such as `dist/blog/[slug]/index.html`. The result is cached, so a new build requires a restart to be picked up. Folders named `api` (at any depth), folders starting with `.`, and `node_modules` are skipped.
302
+ When a base path is set, only paths under it are served; other paths get the plain-text `404 Not found`.
280
303
 
281
- | Folder | Matches |
282
- | --- | --- |
283
- | `blog/[slug]` | `/blog/anything` (exactly one segment in that position) |
284
- | `docs/[...path]` | `/docs/a`, `/docs/a/b` (at least one segment) |
285
- | `docs/[[...path]]` | `/docs`, `/docs/a`, `/docs/a/b` (zero or more segments) |
304
+ ### Paths that are never served
286
305
 
287
- Bracketed segments match any value and other segments must match exactly. Shell pages are checked in the order the scan found them, and the first match wins; there is no ranking by specificity.
306
+ - `dist/api/` (the compiled API code) and anything else whose first segment is `api`.
307
+ - Any path with a segment that starts with `.` (such as `.bini`), except `.well-known`. These return `404`.
308
+ - Paths with a `..` segment, a backslash, or a null byte, or that resolve outside `dist/`, and URLs with invalid percent-encoding, return `400 Bad request`.
288
309
 
289
310
  ### Supported MIME Types
290
311
 
291
312
  | Extensions | Content-Type |
292
313
  | --- | --- |
293
314
  | `.html` | `text/html; charset=utf-8` |
294
- | `.js`, `.mjs` | `application/javascript` |
295
- | `.css` | `text/css` |
296
- | `.json`, `.map` | `application/json` |
315
+ | `.js`, `.mjs` | `text/javascript; charset=utf-8` |
316
+ | `.css` | `text/css; charset=utf-8` |
317
+ | `.json`, `.map` | `application/json; charset=utf-8` |
297
318
  | `.png` | `image/png` |
298
319
  | `.jpg`, `.jpeg` | `image/jpeg` |
299
320
  | `.gif` | `image/gif` |
300
- | `.svg` | `image/svg+xml` |
321
+ | `.svg` | `image/svg+xml; charset=utf-8` |
301
322
  | `.ico` | `image/x-icon` |
302
323
  | `.webp` | `image/webp` |
303
324
  | `.avif` | `image/avif` |
304
325
  | `.woff` | `font/woff` |
305
326
  | `.woff2` | `font/woff2` |
306
327
  | `.ttf` | `font/ttf` |
328
+ | `.otf` | `font/otf` |
307
329
  | `.eot` | `application/vnd.ms-fontobject` |
308
- | `.txt` | `text/plain` |
309
- | `.xml` | `application/xml` |
310
- | `.webmanifest` | `application/manifest+json` |
330
+ | `.txt` | `text/plain; charset=utf-8` |
331
+ | `.xml` | `application/xml; charset=utf-8` |
332
+ | `.webmanifest` | `application/manifest+json; charset=utf-8` |
333
+ | `.pdf` | `application/pdf` |
334
+ | `.wasm` | `application/wasm` |
335
+ | `.mp4` | `video/mp4` |
336
+ | `.webm` | `video/webm` |
337
+ | `.mp3` | `audio/mpeg` |
311
338
 
312
- Any other extension is served as `application/octet-stream`. Every file response also carries `Content-Length`, `ETag`, `Cache-Control`, and `X-Powered-By: Bini.js`.
339
+ Any other extension is served as `application/octet-stream`. Every file response also carries `ETag`, `Cache-Control`, and `X-Content-Type-Options: nosniff`, plus `Content-Length` when the response is not compressed.
313
340
 
314
341
  ### Cache Headers
315
342
 
316
- | File Type | Cache Policy |
343
+ | File | Cache policy |
317
344
  | --- | --- |
318
- | **Files whose absolute path contains an `assets` folder** | `public, max-age=31536000, immutable` (1 year) |
319
- | **All other files** | `no-cache` |
345
+ | A hashed file under `assets/` | `public, max-age=31536000, immutable` (1 year) |
346
+ | Everything else | `no-cache` |
320
347
 
321
- The `assets` check is made on the full absolute file path, not only the part inside `dist/`.
348
+ A file counts as hashed when it is inside `dist/assets/` and its name ends with a separator (`-` or `.`) followed by 8 characters from `A-Z`, `a-z`, `0-9`, `_`, and `-`, at least one of them a digit (for example `assets/index-Bx3k9a2q.js`). Other files in `assets/` get `no-cache`.
322
349
 
323
350
  ### ETag Support
324
351
 
325
- ETags are generated from the file `size` and `mtimeMs`:
352
+ - An `ETag` header is sent on every file response. It is the first 16 characters of an MD5 hex digest of the file's size and modified time, in quotes. For compressed responses, `-br` or `-gzip` is added inside the quotes.
353
+ - A request whose `If-None-Match` matches the ETag (a list of tags, weak `W/` tags, and `*` are understood) receives `304 Not Modified`. This check is skipped when the response is `404.html`, so a missing URL is never reported as unchanged.
326
354
 
327
- - An `ETag` header is sent on every file response (the first 16 characters of an MD5 hex digest of those two values).
328
- - A request whose `If-None-Match` header equals the ETag exactly receives `304 Not Modified`. This check is skipped for the `404.html` response.
355
+ ### Compression
329
356
 
330
- bini-server does not compress responses.
357
+ Compression is off by default. With `BINI_COMPRESS` on, `.html`, `.js`, `.mjs`, `.css`, `.json`, `.svg`, `.txt`, `.xml`, `.webmanifest`, and `.map` files of at least 1 KB are compressed with Brotli (quality 4) or gzip, whichever the client accepts, preferring Brotli. Those responses carry `Vary: Accept-Encoding` and `Content-Encoding`, and no `Content-Length`.
331
358
 
332
359
  ---
333
360
 
334
361
  ## Deployment Notes
335
362
 
336
363
  - The server resolves `dist` (or `DIST_DIR`) against the process's current working directory, so start it from your project root.
337
- - It listens on `0.0.0.0`.
338
- - Set `PORT` (or `BINI_PORT` / `VITE_PORT`) to choose the starting port.
339
- - On `SIGTERM` or `SIGINT` it stops accepting connections and exits with code 0 once the server has closed, or with code 1 after 10 seconds.
364
+ - It listens on `0.0.0.0` unless `BINI_HOST` says otherwise.
365
+ - Set `PORT` (or `BINI_PORT` / `VITE_PORT`) to choose the port. When it is set, the server does not look for another port.
366
+ - Behind a reverse proxy, set `BINI_TRUST_PROXY=1` if your API code needs the original protocol and host in `request.url`.
367
+ - On `SIGTERM` or `SIGINT` it stops accepting connections, closes idle connections, and exits with code 0 once the server has closed. After 10 seconds it closes the remaining connections and exits with code 1. A second signal exits immediately with code 1.
368
+ - An unhandled promise rejection or uncaught exception is logged and exits with code 1.
340
369
  - Keyboard shortcuts are disabled when stdin is not a terminal.
341
- - Fixed (not configurable) server settings: keep-alive timeout 65 s, headers timeout 66 s, max 2000 headers, and `Connection: keep-alive` on every response.
370
+ - Fixed (not configurable) server settings: keep-alive timeout 65 s, headers timeout 66 s, and max 2000 headers.
342
371
 
343
372
  ---
344
373
 
@@ -349,8 +378,10 @@ bini-server does not compress responses.
349
378
  | Body size limit (API) | 10 MB | `BODY_SIZE_LIMIT` |
350
379
  | Body read timeout (API) | 30 s | `BODY_TIMEOUT_SECS` |
351
380
  | Handler timeout (API) | 30 s | `HANDLER_TIMEOUT_SECS` |
352
- | Path traversal | `..` segments and null bytes are not served | Not configurable |
353
- | Compiled API files | `dist/api/` is never served as static files | Not configurable |
381
+ | Path traversal | `..` segments, backslashes, and null bytes are rejected with `400` | Not configurable |
382
+ | Compiled API files and dotfolders | `dist/api/` and dot-prefixed paths (except `.well-known`) are never served | Not configurable |
383
+ | Static methods | Only `GET` and `HEAD`; others get `405` | Not configurable |
384
+ | Forwarded headers | Ignored | `BINI_TRUST_PROXY` |
354
385
  | Error messages | `500` responses hide the message when `NODE_ENV=production` | `NODE_ENV` |
355
386
  | CORS | Not handled by bini-server | n/a |
356
387
 
@@ -362,9 +393,18 @@ bini-server does not compress responses.
362
393
  # Check static files
363
394
  curl http://localhost:3000/
364
395
 
396
+ # Check the health endpoint
397
+ curl http://localhost:3000/__health
398
+
365
399
  # Check an API route (if your API bundle handles it)
366
400
  curl http://localhost:3000/api/hello
367
401
 
402
+ # Check an unknown page URL: 200 with the SPA shell (404 only without 200.html)
403
+ curl -I http://localhost:3000/not-a-real-page
404
+
405
+ # Check a missing file: 404
406
+ curl -I http://localhost:3000/missing.js
407
+
368
408
  # Check ETag (use a file that exists in dist/)
369
409
  curl -I http://localhost:3000/assets/app.js
370
410
 
@@ -390,7 +430,14 @@ BODY_SIZE_LIMIT=10485760
390
430
  ### Served under a sub-path
391
431
 
392
432
  ```bash
393
- BASE=/app
433
+ BINI_BASE=/app
434
+ ```
435
+
436
+ ### Behind a reverse proxy with compression
437
+
438
+ ```bash
439
+ BINI_TRUST_PROXY=1
440
+ BINI_COMPRESS=1
394
441
  ```
395
442
 
396
443
  ### Smaller request bodies
@@ -412,32 +459,37 @@ BODY_TIMEOUT_SECS=300 # 5 minutes
412
459
 
413
460
  ### Environment Variables Priority
414
461
 
462
+ For `PORT`, `DIST_DIR`, `BODY_TIMEOUT_SECS`, `HANDLER_TIMEOUT_SECS`, and `BODY_SIZE_LIMIT`:
463
+
415
464
  1. `BINI_*` (highest)
416
465
  2. `VITE_*` (medium)
417
466
  3. No prefix (lowest)
418
467
 
468
+ `BASE` follows `BINI_BASE`, then `VITE_BASE`, then the unprefixed `BASE`. `BINI_HOST`, `BINI_TRUST_PROXY`, and `BINI_COMPRESS` are read only with the `BINI_` prefix.
469
+
419
470
  ### HTTP Status Codes Produced by bini-server
420
471
 
421
472
  API handlers may return any status.
422
473
 
423
474
  | Code | Description |
424
475
  | --- | --- |
425
- | `200` | Success |
476
+ | `200` | Success, including the `200.html` shell for page URLs and `/__health` |
426
477
  | `304` | Not Modified (ETag match) |
427
- | `400` | Bad request URL (API requests) |
428
- | `404` | Missing file or unknown path (plain-text `Not found`), or `404.html` for an unknown extensionless path when it exists |
429
- | `408` | API request body not received within `BODY_TIMEOUT_SECS`, or another error while reading it |
478
+ | `400` | Bad request: unsafe or malformed path, invalid percent-encoding, bad API request URL, or an error while reading the API request body |
479
+ | `404` | Missing file, denied path, or unknown path (plain-text `Not found`), or `404.html` for a page URL when there is no `200.html` |
480
+ | `405` | A non-API request with a method other than `GET` or `HEAD` (`Allow: GET, HEAD`) |
481
+ | `408` | API request body not received within `BODY_TIMEOUT_SECS` |
430
482
  | `413` | API request body larger than `BODY_SIZE_LIMIT` |
431
- | `500` | API handler error or handler timeout, API bundle failed to load, or an error in a request middleware |
432
- | `503` | `dist/api/index.mjs` is missing (`No API routes compiled`) |
483
+ | `500` | API handler error or handler timeout, or an error in a request middleware |
484
+ | `503` | The API bundle could not be loaded (`failed to load handler`) |
433
485
 
434
- The `408` and `413` cases destroy the incoming request before the response is written, so a client may see a closed connection instead of the JSON error.
486
+ The `408` and `413` responses are sent with `Connection: close`.
435
487
 
436
488
  With `NODE_ENV=production` the message in `500` responses from handler errors is always `Internal server error`.
437
489
 
438
490
  ### Supported HTTP Methods
439
491
 
440
- All methods are passed to the API bundle, which decides which it accepts. Static file responses do not check the method, and `HEAD` receives headers only.
492
+ API requests accept every method; the bundle decides which it handles. All other requests accept only `GET` and `HEAD`, and `HEAD` receives headers only.
441
493
 
442
494
  ---
443
495