bini-server 2.0.1 → 2.0.2

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
@@ -2,12 +2,11 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/bini-server?style=flat-square&logo=npm&logoColor=white&label=npm&color=CB3837&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
4
4
  [![license](https://img.shields.io/badge/license-MIT-green?style=flat-square&logo=opensourceinitiative&logoColor=white&labelColor=0a0a0a)](./LICENSE)
5
- [![node](https://img.shields.io/badge/node-%3E%3D20-339933?style=flat-square&logo=nodedotjs&logoColor=white&labelColor=0a0a0a)](https://nodejs.org)
6
5
  [![bundle size](https://img.shields.io/bundlephobia/min/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://bundlephobia.com/package/bini-server)
7
6
  [![downloads](https://img.shields.io/npm/dt/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
8
7
 
9
- **Production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
10
- Serves the output of `vite build`: pre-rendered pages, static assets, and the compiled API bundle. It uses 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
+ 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).
11
10
 
12
11
  ---
13
12
 
@@ -19,10 +18,10 @@ Serves the output of `vite build`: pre-rendered pages, static assets, and the co
19
18
  - [Usage](#usage)
20
19
  - [Keyboard Shortcuts](#keyboard-shortcuts)
21
20
  - [Environment Variables](#environment-variables)
22
- - [Project Structure](#project-structure)
21
+ - [Expected Build Output](#expected-build-output)
23
22
  - [API Routes](#api-routes)
24
23
  - [Static File Serving](#static-file-serving)
25
- - [Deployment](#deployment)
24
+ - [Deployment Notes](#deployment-notes)
26
25
  - [Security](#security)
27
26
  - [Verifying the Server](#verifying-the-server)
28
27
  - [Configuration Examples](#configuration-examples)
@@ -36,37 +35,36 @@ Serves the output of `vite build`: pre-rendered pages, static assets, and the co
36
35
 
37
36
  ### Core
38
37
 
39
- - **Static file serving.** Streams `dist/` with MIME types, ETag, and cache headers.
40
- - **API routes.** Serves `/api/*` from the compiled bundle `dist/api/index.mjs`, which `vite build` produces from `src/app/api/`.
41
- - **Route-aware fallbacks.** Pre-rendered pages first, then shell pages for dynamic routes, then `404.html`, then `index.html`.
42
- - **ETag support.** `304 Not Modified` responses for unchanged static files.
38
+ - **Static file serving.** Streams files from `dist/` with MIME types, an `ETag`, and `Cache-Control` headers.
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.
43
42
  - **Sub-path deployments.** Serve the app under a `BASE` path.
44
43
 
45
44
  ### Security and Reliability
46
45
 
47
46
  - **Body limits.** Configurable request body size limit for API requests (default 10 MB).
48
47
  - **Timeouts.** Configurable body read and handler timeouts (default 30 s each).
49
- - **Path traversal protection.** Requests containing a `..` segment or a null byte are not served, and `dist/api/` is never served as a static file.
50
- - **Error hiding in production.** With `NODE_ENV=production`, error responses say only `Internal server error`.
51
- - **Port auto-increment.** Starts at `3000` and tries the next port while one is busy, up to 99 higher. Each busy port is logged.
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
+ - **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.
52
51
 
53
52
  ### Operations
54
53
 
55
- - **Auto env loading.** `.env` files are loaded at startup and listed in the banner.
56
- - **Interactive shortcuts.** `h` for help, `o` to open the browser, `q` to quit.
57
- - **Cross-platform browser opening.** `o` uses `start`, `open`, or `xdg-open` depending on the platform.
58
- - **Graceful shutdown.** Handles `SIGTERM` and `SIGINT` with a timeout fallback.
54
+ - **Env file loading.** Environment files are loaded through bini-env at startup, and the banner lists the files bini-env reports.
55
+ - **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.
59
57
  - **Flexible config.** Supports `BINI_*`, `VITE_*`, or unprefixed environment variables.
60
58
 
61
59
  ---
62
60
 
63
61
  ## Requirements
64
62
 
65
- - Node.js **≥ 20.19.0**
66
- - A [bini-router](https://www.npmjs.com/package/bini-router) project with a finished `vite build`:
67
- - `dist/` (required; the server exits if it is missing)
68
- - `dist/api/index.mjs` (only for API routes; it must export `fetch()`)
69
- - pre-rendered pages, `404.html`, and shell pages from [bini-ssg](https://www.npmjs.com/package/bini-ssg) (optional)
63
+ - Node.js (the server uses the global `Request` and `Response` classes, `Headers#getSetCookie`, and `Readable.fromWeb`)
64
+ - A finished build in `dist/` (relative to the working directory):
65
+ - `dist/` (required; the server exits with code 1 if it is missing)
66
+ - `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)
70
68
 
71
69
  ---
72
70
 
@@ -106,14 +104,16 @@ npm start # Serve in production
106
104
 
107
105
  ```text
108
106
  ß Bini.js (production)
109
- ➜ Environments: .env.local, .env
107
+ ➜ Environments: .env
110
108
  ➜ Local: http://localhost:3000/
111
109
  ➜ Network: http://192.168.1.5:3000/
112
110
  ➜ press h + enter to show help
113
111
  ```
114
112
 
115
- - `Environments` lists the `.env` files that were found, relative to the working directory, and is omitted when there are none.
116
- - `Network` is the first private IPv4 address of a non-internal interface, skipping virtual interfaces such as Docker and VPN adapters. If there is none, it falls back to the first non-internal IPv4 address, and it is omitted when no address is found.
113
+ - `(production)` is always printed.
114
+ - `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
117
  - `Base` appears as an extra line when `BASE` is set.
118
118
 
119
119
  ### Programmatic start
@@ -128,12 +128,14 @@ await start()
128
128
 
129
129
  ### What `start()` does
130
130
 
131
- 1. Loads `.env` files from the working directory and re-reads the configuration.
132
- 2. Exits with code 1 when the `dist` directory does not exist.
133
- 3. Loads `dist/api/index.mjs` (a warning is printed if it is missing, see [API Routes](#api-routes)).
134
- 4. Scans `dist` once for shell pages.
135
- 5. Finds a free port, starting at `PORT` (see [Port selection](#port-selection)).
136
- 6. Starts the HTTP server on `0.0.0.0`, prints the banner, and starts the keyboard shortcuts.
131
+ 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.
137
+
138
+ `dist/api/index.mjs` is **not** loaded at startup. It is loaded on the first API request (see [API Routes](#api-routes)).
137
139
 
138
140
  ---
139
141
 
@@ -147,7 +149,7 @@ While the server is running, type a key and press `enter`:
147
149
  | `o` | Open `http://localhost:<port><base>/` in the default browser |
148
150
  | `q` | Quit the server |
149
151
 
150
- > Keyboard shortcuts are disabled when stdin is not a terminal (for example in CI/CD or most hosted platforms). When stdin closes, the process exits.
152
+ > Keyboard shortcuts are only enabled when stdin is a terminal. While they are active, closing stdin exits the process.
151
153
 
152
154
  ---
153
155
 
@@ -155,14 +157,7 @@ While the server is running, type a key and press `enter`:
155
157
 
156
158
  ### `.env` Files
157
159
 
158
- At startup, bini-server loads these files from the working directory, when they exist. They are listed from highest to lowest priority, with `[mode]` being `NODE_ENV` (or `production` when it is not set):
159
-
160
- 1. `.env.[mode].local`
161
- 2. `.env.[mode]`
162
- 3. `.env.local`
163
- 4. `.env`
164
-
165
- A variable that is already set in the environment is never overridden by a file, and a higher-priority file wins over a lower one. The loaded values are available through `process.env`, which is also what API routes receive as `env`. The server settings below can come from these files too.
160
+ At startup, bini-server calls bini-env's `loadEnvFiles` for the working directory, using `NODE_ENV` as the mode (or `production` when it is not set), and then re-reads its own configuration. Which files are loaded and in what priority is defined by bini-env; see its documentation.
166
161
 
167
162
  ### Server Configuration
168
163
 
@@ -176,16 +171,16 @@ All settings support **three naming conventions:**
176
171
 
177
172
  | Variable | Default | Description |
178
173
  | --- | --- | --- |
179
- | `PORT` | `3000` | HTTP port to listen on. If it is in use, the next free port is used (see [Port selection](#port-selection)) |
174
+ | `PORT` | `3000` | Port to start from. If it is in use, the next free port is used (see [Port selection](#port-selection)) |
180
175
  | `DIST_DIR` | `dist` | Build output folder, relative to the working directory |
181
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`) |
182
177
  | `BODY_TIMEOUT_SECS` | `30` | Max seconds to read an API request body |
183
178
  | `HANDLER_TIMEOUT_SECS` | `30` | Max seconds for the API handler to respond |
184
179
  | `BODY_SIZE_LIMIT` | `10485760` | Max API request body size in bytes (10 MB) |
185
180
 
186
- Values that are not numbers fall back to the default. Setting a limit or timeout to `0` does **not** disable it: a body limit of `0` rejects any request body, and a timeout of `0` expires immediately.
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.
187
182
 
188
- The server also reads `NODE_ENV`. When it is `production`, error responses hide the underlying message.
183
+ 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.
189
184
 
190
185
  ### Port selection
191
186
 
@@ -195,55 +190,40 @@ The server checks `PORT`, then each following port, until it finds one that is f
195
190
  Port 3000 is in use, trying another one...
196
191
  ```
197
192
 
198
- The banner then shows the port that was actually used in the `Local` and `Network` URLs. The search covers 100 ports (`PORT` through `PORT + 99`); if none is free, `start()` fails with `No free port found in range <start>–<end>`.
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>`.
199
194
 
200
195
  ### Examples
201
196
 
202
197
  ```bash
203
- # .env file
204
- PORT=8080
205
- BODY_SIZE_LIMIT=5242880 # 5MB
206
-
207
- # Or inline
198
+ # Inline
208
199
  PORT=3001 bini-server
209
200
 
210
- # Or with the BINI prefix (takes precedence over PORT)
201
+ # With the BINI prefix (takes precedence over PORT)
211
202
  BINI_PORT=3002 bini-server
212
203
  ```
213
204
 
214
205
  ---
215
206
 
216
- ## Project Structure
207
+ ## Expected Build Output
208
+
209
+ bini-server serves whatever is in `dist/` (or `DIST_DIR`). It does not read your source files at runtime.
217
210
 
218
211
  ```text
219
- my-app/
220
- ├── dist/ # Built output (required)
221
- │ ├── index.html
222
- │ ├── about/index.html # Pre-rendered pages (bini-ssg)
223
- │ ├── blog/[slug]/index.html # Shell page for a dynamic route (bini-ssg)
224
- │ ├── 404.html
225
- │ ├── assets/
226
- │ └── api/
227
- │ └── index.mjs # Compiled API bundle (not served as a file)
228
- ├── src/
229
- │ ├── app/
230
- │ │ ├── api/ # API handlers, compiled into dist/api at build time
231
- │ │ │ ├── users.ts
232
- │ │ │ └── posts/
233
- │ │ │ ├── index.ts
234
- │ │ │ └── [id].ts
235
- │ │ └── layout.tsx
236
- │ └── main.tsx
237
- ├── .env # Environment variables
238
- ├── package.json
239
- └── vite.config.ts
212
+ dist/
213
+ ├── index.html
214
+ ├── about/index.html # Pre-rendered page
215
+ ├── blog/[slug]/index.html # Shell page for a dynamic route
216
+ ├── 404.html
217
+ ├── assets/
218
+ └── api/
219
+ └── index.mjs # API bundle (never served as a file)
240
220
  ```
241
221
 
242
222
  ---
243
223
 
244
224
  ## API Routes
245
225
 
246
- Requests to `<base>/api` and `<base>/api/...` are passed to the `fetch` export of `dist/api/index.mjs`, which `vite build` produces when `src/app/api` exists. bini-server does not read `src/` at runtime. The bundle is loaded once, at startup.
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.
247
227
 
248
228
  ### What the bundle receives
249
229
 
@@ -251,63 +231,28 @@ Requests to `<base>/api` and `<base>/api/...` are passed to the `fetch` export o
251
231
  fetch(request: Request, env: NodeJS.ProcessEnv, ctx: { waitUntil(p: Promise<unknown>): void })
252
232
  ```
253
233
 
254
- - **`request`:** a standard `Request` whose URL is `http://<host header><original request URL>`. Header arrays are joined with a comma and a space (the `cookie` header with a semicolon and a space), and the body is read for every method except `GET` and `HEAD`.
255
- - **`env`:** `process.env`, so [bini-env](https://www.npmjs.com/package/bini-env)'s `getEnv(c, key)` sees the same values, including those loaded from `.env` files.
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`.
256
236
  - **`ctx.waitUntil`:** accepts a promise and swallows its rejection; the server does not wait for it.
257
237
 
258
238
  The response status and headers (including every `Set-Cookie`) are copied, and the body is streamed to the client. `HEAD` requests receive headers only.
259
239
 
260
- ### Supported handler formats
261
-
262
- How handlers are written, routed, and matched is defined by bini-router. For example:
263
-
264
- ```typescript
265
- // src/app/api/hello.ts
266
-
267
- // 1. Hono app (default export with .fetch)
268
- import { Hono } from 'hono'
269
- const app = new Hono()
270
- app.get('/hello', (c) => c.json({ message: 'Hello' }))
271
- export default app
272
-
273
- // 2. Plain function (default export)
274
- export default (req: Request) => Response.json({ message: 'Hello' })
275
-
276
- // 3. Per-method exports
277
- export function GET(req: Request, { params }) {
278
- return Response.json({ id: params.id })
279
- }
280
- ```
281
-
282
- Only `.ts` and `.js` files in `src/app/api/` are used.
283
-
284
- ### Dynamic routes
285
-
286
- ```text
287
- src/app/api/
288
- users/
289
- [id].ts → /api/users/:id
290
- posts/
291
- [...slug].ts → /api/posts/*
292
- ```
293
-
294
- Route parameters arrive in the second argument of a handler (`{ params, searchParams, env, waitUntil }`). See the [bini-router](https://www.npmjs.com/package/bini-router) documentation for the full routing rules.
295
-
296
240
  ### CORS
297
241
 
298
- bini-server does not add CORS headers or answer preflight requests itself. CORS is handled by the compiled bundle and is controlled by the `cors` option of `biniroute()` in `vite.config.ts` (it is off by default).
242
+ bini-server does not add CORS headers or answer preflight requests. Any CORS handling has to come from the API bundle.
299
243
 
300
244
  ### Base path
301
245
 
302
- bini-server and the compiled API each check the base path, so set `BASE` to the sub-path your app was built for.
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.
303
247
 
304
248
  ### Request limits
305
249
 
306
- The server's `BODY_SIZE_LIMIT` applies, and so does the bundle's own `bodySizeLimit` (the `biniroute()` option, 1 MB by default), so the lower of the two limits is the one you hit.
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.
307
251
 
308
- ### When the bundle is missing
252
+ ### When the bundle is missing or broken
309
253
 
310
- If `dist/api/index.mjs` is missing or does not export `fetch()`, the server prints a warning at startup, and every API request returns `404` with `{"error":"No API routes compiled"}`.
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"}`.
311
256
 
312
257
  ---
313
258
 
@@ -315,23 +260,23 @@ If `dist/api/index.mjs` is missing or does not export `fetch()`, the server prin
315
260
 
316
261
  ### Lookup order
317
262
 
318
- For a path **with** a file extension, 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`.
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`.
319
264
 
320
265
  For a path **without** an extension, the server uses the first of these that applies:
321
266
 
322
267
  | Order | Looks for | Status |
323
268
  | --- | --- | --- |
324
269
  | 1 | `dist/<path>/index.html` (pre-rendered page) | 200 |
325
- | 2 | A shell page whose folder name matches the path | 200 |
270
+ | 2 | The `index.html` of a matching shell page | 200 |
326
271
  | 3 | `dist/404.html` | 404 |
327
- | 4 | `dist/index.html` (client-side fallback) | 200 |
328
- | 5 | Nothing found | plain-text 404 |
272
+ | 4 | `dist/index.html` | 200 |
273
+ | 5 | Nothing found (plain-text `Not found`) | 404 |
329
274
 
330
- When `BASE` is set, only paths under it are served.
275
+ When `BASE` is set, only paths under it are served; other paths get the plain-text `404 Not found`.
331
276
 
332
277
  ### Shell pages
333
278
 
334
- 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`. A new build requires a restart to be picked up. Folders named `api`, dot-folders, and `node_modules` are skipped.
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.
335
280
 
336
281
  | Folder | Matches |
337
282
  | --- | --- |
@@ -339,89 +284,61 @@ At startup the server scans `dist` once for folders whose names are wrapped in s
339
284
  | `docs/[...path]` | `/docs/a`, `/docs/a/b` (at least one segment) |
340
285
  | `docs/[[...path]]` | `/docs`, `/docs/a`, `/docs/a/b` (zero or more segments) |
341
286
 
342
- Bracketed segments match any value, other segments must match exactly, and the first matching shell wins; there is no ranking by specificity.
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.
343
288
 
344
289
  ### Supported MIME Types
345
290
 
346
- | Type | Extensions |
291
+ | Extensions | Content-Type |
347
292
  | --- | --- |
348
- | Documents and code | `.html`, `.js`, `.mjs`, `.css`, `.json`, `.map`, `.txt`, `.xml`, `.webmanifest` |
349
- | Images | `.png`, `.jpg`, `.jpeg`, `.gif`, `.svg`, `.webp`, `.avif`, `.ico` |
350
- | Fonts | `.woff`, `.woff2`, `.ttf`, `.eot` |
351
-
352
- Any other extension is served as `application/octet-stream`. Every file response also carries `Content-Length` and `X-Powered-By: Bini.js`.
293
+ | `.html` | `text/html; charset=utf-8` |
294
+ | `.js`, `.mjs` | `application/javascript` |
295
+ | `.css` | `text/css` |
296
+ | `.json`, `.map` | `application/json` |
297
+ | `.png` | `image/png` |
298
+ | `.jpg`, `.jpeg` | `image/jpeg` |
299
+ | `.gif` | `image/gif` |
300
+ | `.svg` | `image/svg+xml` |
301
+ | `.ico` | `image/x-icon` |
302
+ | `.webp` | `image/webp` |
303
+ | `.avif` | `image/avif` |
304
+ | `.woff` | `font/woff` |
305
+ | `.woff2` | `font/woff2` |
306
+ | `.ttf` | `font/ttf` |
307
+ | `.eot` | `application/vnd.ms-fontobject` |
308
+ | `.txt` | `text/plain` |
309
+ | `.xml` | `application/xml` |
310
+ | `.webmanifest` | `application/manifest+json` |
311
+
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`.
353
313
 
354
314
  ### Cache Headers
355
315
 
356
316
  | File Type | Cache Policy |
357
317
  | --- | --- |
358
- | **Files inside an `assets/` folder** | `public, max-age=31536000, immutable` (1 year) |
318
+ | **Files whose absolute path contains an `assets` folder** | `public, max-age=31536000, immutable` (1 year) |
359
319
  | **All other files** | `no-cache` |
360
320
 
321
+ The `assets` check is made on the full absolute file path, not only the part inside `dist/`.
322
+
361
323
  ### ETag Support
362
324
 
363
325
  ETags are generated from the file `size` and `mtimeMs`:
364
326
 
365
- - An `ETag` header is sent on every file response (an MD5 hash of those two values, 16 characters).
366
- - A request whose `If-None-Match` equals the ETag exactly receives `304 Not Modified` (for `200` responses).
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.
367
329
 
368
330
  bini-server does not compress responses.
369
331
 
370
332
  ---
371
333
 
372
- ## Deployment
373
-
374
- ### What to ship
375
-
376
- bini-server needs the build output, not your source: deploy `dist/` (including `dist/api/index.mjs`), `package.json`, and the installed dependencies. The compiled API leaves packages from `node_modules` external, so dependencies must be installed on the server.
377
-
378
- - **VPS / pm2:** deploy the project directory, install dependencies, and build
379
- - **Railway, Render, Fly.io:** build as part of the deploy
380
- - **Docker:** build inside the image, as shown below
381
-
382
- ### VPS / Dedicated Server
383
-
384
- ```bash
385
- npm run build
386
- npm start
387
-
388
- # With pm2 (recommended)
389
- npm install -g pm2
390
- pm2 start "npm start" --name my-app
391
- pm2 save
392
- pm2 startup
393
- ```
394
-
395
- ### Platform as a Service
396
-
397
- | Platform | Start Command | Notes |
398
- | --- | --- | --- |
399
- | **Railway** | `npm start` | PORT injected automatically |
400
- | **Render** | `npm start` | PORT injected automatically |
401
- | **Fly.io** | `npm start` | See the fly.toml example below |
402
- | **Heroku** | `npm start` | PORT injected automatically |
403
-
404
- ### Docker
405
-
406
- ```dockerfile
407
- FROM node:20-alpine
408
- WORKDIR /app
409
- COPY package*.json ./
410
- RUN npm ci
411
- COPY . .
412
- RUN npm run build && npm prune --omit=dev
413
- ENV NODE_ENV=production
414
- EXPOSE 3000
415
- CMD ["npm", "start"]
416
- ```
334
+ ## Deployment Notes
417
335
 
418
- ### Fly.io
419
-
420
- ```toml
421
- # fly.toml
422
- [processes]
423
- app = "npm start"
424
- ```
336
+ - 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.
340
+ - 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.
425
342
 
426
343
  ---
427
344
 
@@ -434,8 +351,8 @@ CMD ["npm", "start"]
434
351
  | Handler timeout (API) | 30 s | `HANDLER_TIMEOUT_SECS` |
435
352
  | Path traversal | `..` segments and null bytes are not served | Not configurable |
436
353
  | Compiled API files | `dist/api/` is never served as static files | Not configurable |
437
- | Error messages | Hidden when `NODE_ENV=production` | `NODE_ENV` |
438
- | CORS | Handled by the compiled API | `biniroute({ cors })` |
354
+ | Error messages | `500` responses hide the message when `NODE_ENV=production` | `NODE_ENV` |
355
+ | CORS | Not handled by bini-server | n/a |
439
356
 
440
357
  ---
441
358
 
@@ -445,10 +362,10 @@ CMD ["npm", "start"]
445
362
  # Check static files
446
363
  curl http://localhost:3000/
447
364
 
448
- # Check API routes
365
+ # Check an API route (if your API bundle handles it)
449
366
  curl http://localhost:3000/api/hello
450
367
 
451
- # Check ETag
368
+ # Check ETag (use a file that exists in dist/)
452
369
  curl -I http://localhost:3000/assets/app.js
453
370
 
454
371
  # Test 304 Not Modified
@@ -489,8 +406,6 @@ BODY_SIZE_LIMIT=104857600 # 100MB
489
406
  BODY_TIMEOUT_SECS=300 # 5 minutes
490
407
  ```
491
408
 
492
- Raise `bodySizeLimit` in `biniroute()` too, otherwise the bundle's own limit still applies.
493
-
494
409
  ---
495
410
 
496
411
  ## API Reference
@@ -501,25 +416,28 @@ Raise `bodySizeLimit` in `biniroute()` too, otherwise the bundle's own limit sti
501
416
  2. `VITE_*` (medium)
502
417
  3. No prefix (lowest)
503
418
 
504
- ### Returned HTTP Status Codes
419
+ ### HTTP Status Codes Produced by bini-server
505
420
 
506
- These are produced by bini-server itself. API handlers may return any status.
421
+ API handlers may return any status.
507
422
 
508
423
  | Code | Description |
509
424
  | --- | --- |
510
425
  | `200` | Success |
511
426
  | `304` | Not Modified (ETag match) |
512
427
  | `400` | Bad request URL (API requests) |
513
- | `404` | Not found (missing file, unknown path, or no compiled API), or `404.html` for unknown page paths |
514
- | `408` | API request body not received in time, or a read error |
515
- | `413` | API request body too large |
516
- | `500` | Internal server error (including API handler timeout) |
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 |
430
+ | `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`) |
433
+
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.
517
435
 
518
- In production (`NODE_ENV=production`) the message in `500` responses is always `Internal server error`.
436
+ With `NODE_ENV=production` the message in `500` responses from handler errors is always `Internal server error`.
519
437
 
520
438
  ### Supported HTTP Methods
521
439
 
522
- All methods are passed to the API bundle, which decides which it accepts. Static responses do not check the method, and `HEAD` receives headers only.
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.
523
441
 
524
442
  ---
525
443