bini-server 2.0.0 โ†’ 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
@@ -1,56 +1,74 @@
1
1
  # bini-server
2
2
 
3
- <div align="center">
4
-
5
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)
6
4
  [![license](https://img.shields.io/badge/license-MIT-green?style=flat-square&logo=opensourceinitiative&logoColor=white&labelColor=0a0a0a)](./LICENSE)
7
- [![node](https://img.shields.io/badge/node-%3E%3D20-339933?style=flat-square&logo=nodedotjs&logoColor=white&labelColor=0a0a0a)](https://nodejs.org)
8
5
  [![bundle size](https://img.shields.io/bundlephobia/min/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://bundlephobia.com/package/bini-server)
9
6
  [![downloads](https://img.shields.io/npm/dt/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
10
7
 
11
- **Production server for [bini-router](https://www.npmjs.com/package/bini-router) apps.**
12
- Zero-dependency, secure-by-default, production-grade server for your static sites and API routes.
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).
10
+
11
+ ---
13
12
 
14
- </div>
13
+ ## Table of Contents
14
+
15
+ - [Features](#features)
16
+ - [Requirements](#requirements)
17
+ - [Install](#install)
18
+ - [Usage](#usage)
19
+ - [Keyboard Shortcuts](#keyboard-shortcuts)
20
+ - [Environment Variables](#environment-variables)
21
+ - [Expected Build Output](#expected-build-output)
22
+ - [API Routes](#api-routes)
23
+ - [Static File Serving](#static-file-serving)
24
+ - [Deployment Notes](#deployment-notes)
25
+ - [Security](#security)
26
+ - [Verifying the Server](#verifying-the-server)
27
+ - [Configuration Examples](#configuration-examples)
28
+ - [API Reference](#api-reference)
29
+ - [Contributing](#contributing)
30
+ - [License](#license)
15
31
 
16
32
  ---
17
33
 
18
- ## โœจ Features
19
-
20
- ### Core Features
21
- - ๐Ÿ—‚๏ธ **Static file serving** โ€” Streams `dist/` with proper MIME types, ETag, and cache headers
22
- - ๐ŸŒ **API routes** โ€” Serves `/api/*` from `src/app/api/` (Hono apps + plain functions)
23
- - ๐Ÿ”€ **SPA fallback** โ€” Unknown routes serve `dist/index.html` automatically
24
- - ๐Ÿท๏ธ **ETag support** โ€” `304 Not Modified` responses for unchanged static files
25
- - โšก **Lazy route loading** โ€” API routes scanned only on first request for fast startup
26
-
27
- ### Security & Performance
28
- - ๐Ÿ›ก๏ธ **CORS** โ€” Enabled by default, configurable via `CORS_ENABLED` (supports `BINI_*`, `VITE_*`, no prefix)
29
- - ๐Ÿ”’ **Body limits** โ€” Configurable request body size limit (default 10MB)
30
- - โฑ๏ธ **Timeouts** โ€” Configurable body read + handler timeouts (default 30s each)
31
- - ๐Ÿšซ **Path traversal protection** โ€” Guards against `..` and `//` in URLs
32
- - ๐Ÿ’พ **Module cache** โ€” Caches imported handlers with mtime invalidation
33
- - ๐Ÿ”Œ **Port auto-increment** โ€” Starts at `3000`, auto-increments if busy
34
-
35
- ### Developer Experience
36
- - ๐ŸŒฟ **Auto env loading** โ€” `.env` files detected and listed at startup
37
- - โŒจ๏ธ **Interactive shortcuts** โ€” `h` for help, `o` to open browser, `q` to quit
38
- - ๐Ÿ–ฅ๏ธ **Cross-platform** โ€” Works on Windows, macOS, and Linux
39
- - ๐Ÿช„ **Graceful shutdown** โ€” Handles `SIGTERM` + `SIGINT` with timeout fallback
40
- - ๐Ÿ“ฆ **Zero dependencies** โ€” Only uses Node.js built-in modules
41
- - ๐Ÿ”ง **Flexible config** โ€” Supports `BINI_*`, `VITE_*`, or no prefix env vars
34
+ ## Features
35
+
36
+ ### Core
37
+
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.
42
+ - **Sub-path deployments.** Serve the app under a `BASE` path.
43
+
44
+ ### Security and Reliability
45
+
46
+ - **Body limits.** Configurable request body size limit for API requests (default 10 MB).
47
+ - **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
+ - **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
+
52
+ ### Operations
53
+
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.
57
+ - **Flexible config.** Supports `BINI_*`, `VITE_*`, or unprefixed environment variables.
42
58
 
43
59
  ---
44
60
 
45
- ## ๐Ÿ“‹ Requirements
61
+ ## Requirements
46
62
 
47
- - Node.js **โ‰ฅ 20.19.0**
48
- - A [bini-router](https://www.npmjs.com/package/bini-router) project with a built `dist/`
49
- - API handlers in `src/app/api/` (if using API routes)
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)
50
68
 
51
69
  ---
52
70
 
53
- ## ๐Ÿ“ฆ Install
71
+ ## Install
54
72
 
55
73
  ```bash
56
74
  npm install bini-server
@@ -62,7 +80,7 @@ yarn add bini-server
62
80
 
63
81
  ---
64
82
 
65
- ## ๐Ÿš€ Usage
83
+ ## Usage
66
84
 
67
85
  ### 1. Add to `package.json`
68
86
 
@@ -84,335 +102,313 @@ npm start # Serve in production
84
102
 
85
103
  ### 3. Terminal Output
86
104
 
87
- ```
88
- รŸ Bini.js (production)
89
- โžœ Environments: .env, .env.local
105
+ ```text
106
+ รŸ Bini.js (production)
107
+ โžœ Environments: .env
90
108
  โžœ Local: http://localhost:3000/
91
109
  โžœ Network: http://192.168.1.5:3000/
92
110
  โžœ press h + enter to show help
93
111
  ```
94
112
 
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
+ - `Base` appears as an extra line when `BASE` is set.
118
+
119
+ ### Programmatic start
120
+
121
+ The module exports a single function:
122
+
123
+ ```js
124
+ import { start } from 'bini-server'
125
+
126
+ await start()
127
+ ```
128
+
129
+ ### What `start()` does
130
+
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)).
139
+
95
140
  ---
96
141
 
97
- ## โŒจ๏ธ Keyboard Shortcuts
142
+ ## Keyboard Shortcuts
98
143
 
99
144
  While the server is running, type a key and press `enter`:
100
145
 
101
146
  | Key | Action |
102
- |-----|--------|
147
+ | --- | --- |
103
148
  | `h` | Show available shortcuts |
104
- | `o` | Open your app in the default browser |
149
+ | `o` | Open `http://localhost:<port><base>/` in the default browser |
105
150
  | `q` | Quit the server |
106
151
 
107
- > Keyboard shortcuts are automatically disabled in non-interactive environments (like Render, CI/CD).
152
+ > Keyboard shortcuts are only enabled when stdin is a terminal. While they are active, closing stdin exits the process.
108
153
 
109
154
  ---
110
155
 
111
- ## ๐ŸŒฟ Environment Variables
112
-
113
- ### Auto-Detected `.env` Files
114
-
115
- At startup, bini-server automatically detects and loads:
156
+ ## Environment Variables
116
157
 
117
- 1. `.env.local`
118
- 2. `.env.[NODE_ENV].local` (e.g., `.env.production.local`)
119
- 3. `.env.[NODE_ENV]` (e.g., `.env.production`)
120
- 4. `.env`
158
+ ### `.env` Files
121
159
 
122
- All detected files are listed in the startup banner.
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.
123
161
 
124
162
  ### Server Configuration
125
163
 
126
- All environment variables support **three naming conventions:**
164
+ All settings support **three naming conventions:**
127
165
 
128
166
  | Convention | Example | Priority |
129
- |------------|---------|----------|
167
+ | --- | --- | --- |
130
168
  | `BINI_*` | `BINI_PORT=3000` | Highest |
131
169
  | `VITE_*` | `VITE_PORT=3000` | Medium |
132
170
  | No prefix | `PORT=3000` | Lowest |
133
171
 
134
172
  | Variable | Default | Description |
135
- |----------|---------|-------------|
136
- | `PORT` | `3000` | HTTP port to listen on |
137
- | `CORS_ENABLED` | `true` | Enable/disable CORS on API routes |
138
- | `API_DIR` | `src/app/api` | Path to API handlers directory |
139
- | `DIST_DIR` | `dist` | Path to static files directory |
140
- | `BODY_TIMEOUT_SECS` | `30` | Max seconds to read request body |
141
- | `HANDLER_TIMEOUT_SECS` | `30` | Max seconds for handler to respond |
142
- | `BODY_SIZE_LIMIT` | `10485760` | Max request body size in bytes (10MB) |
173
+ | --- | --- | --- |
174
+ | `PORT` | `3000` | Port to start from. If it is in use, the next free port is used (see [Port selection](#port-selection)) |
175
+ | `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
+ | `BODY_TIMEOUT_SECS` | `30` | Max seconds to read an API request body |
178
+ | `HANDLER_TIMEOUT_SECS` | `30` | Max seconds for the API handler to respond |
179
+ | `BODY_SIZE_LIMIT` | `10485760` | Max API request body size in bytes (10 MB) |
180
+
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.
182
+
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.
184
+
185
+ ### Port selection
186
+
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:
188
+
189
+ ```text
190
+ Port 3000 is in use, trying another one...
191
+ ```
192
+
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>`.
143
194
 
144
195
  ### Examples
145
196
 
146
197
  ```bash
147
- # .env file
148
- PORT=8080
149
- CORS_ENABLED=false
150
- API_DIR=src/api
151
- BODY_SIZE_LIMIT=5242880 # 5MB
152
-
153
- # Or inline
154
- PORT=3001 BINI_CORS_ENABLED=false bini-server
198
+ # Inline
199
+ PORT=3001 bini-server
155
200
 
156
- # Or with VITE prefix
157
- VITE_PORT=3000 VITE_CORS_ENABLED=false bini-server
201
+ # With the BINI prefix (takes precedence over PORT)
202
+ BINI_PORT=3002 bini-server
158
203
  ```
159
204
 
160
205
  ---
161
206
 
162
- ## ๐Ÿ“ Project Structure
207
+ ## Expected Build Output
163
208
 
164
- ```
165
- my-app/
166
- โ”œโ”€โ”€ dist/ # Built static files (required)
167
- โ”‚ โ”œโ”€โ”€ index.html
168
- โ”‚ โ”œโ”€โ”€ assets/
169
- โ”‚ โ””โ”€โ”€ ...
170
- โ”œโ”€โ”€ src/
171
- โ”‚ โ”œโ”€โ”€ app/
172
- โ”‚ โ”‚ โ”œโ”€โ”€ api/ # API handlers (optional)
173
- โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ users.ts
174
- โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ posts/
175
- โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ index.ts
176
- โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ [id].ts
177
- โ”‚ โ”‚ โ””โ”€โ”€ layout.tsx
178
- โ”‚ โ””โ”€โ”€ main.tsx
179
- โ”œโ”€โ”€ .env # Environment variables
180
- โ”œโ”€โ”€ package.json
181
- โ””โ”€โ”€ vite.config.ts
209
+ bini-server serves whatever is in `dist/` (or `DIST_DIR`). It does not read your source files at runtime.
210
+
211
+ ```text
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)
182
220
  ```
183
221
 
184
222
  ---
185
223
 
186
- ## ๐ŸŒ API Routes
224
+ ## API Routes
187
225
 
188
- ### Supported Formats
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.
189
227
 
190
- ```typescript
191
- // 1. Hono App (Recommended)
192
- import { Hono } from 'hono';
193
- const app = new Hono();
194
- app.get('/users', (c) => c.json({ users: [] }));
195
- export default app;
228
+ ### What the bundle receives
196
229
 
197
- // 2. Plain Function
198
- export default (req: Request) => {
199
- return Response.json({ message: 'Hello' });
200
- };
230
+ ```ts
231
+ fetch(request: Request, env: NodeJS.ProcessEnv, ctx: { waitUntil(p: Promise<unknown>): void })
201
232
  ```
202
233
 
203
- ### Supported Extensions
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.
204
237
 
205
- Only `.ts` and `.js` files are supported for API routes (Next.js convention).
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.
206
239
 
207
- ### Dynamic Routes
240
+ ### CORS
208
241
 
209
- ```
210
- src/app/api/
211
- users/
212
- [id].ts โ†’ /api/users/:id
213
- posts/
214
- [...slug].ts โ†’ /api/posts/*
215
- ```
242
+ bini-server does not add CORS headers or answer preflight requests. Any CORS handling has to come from the API bundle.
216
243
 
217
- ### Route Parameters
244
+ ### Base path
218
245
 
219
- ```typescript
220
- // src/app/api/users/[id].ts
221
- export default (req: Request) => {
222
- const params = JSON.parse(req.headers.get('x-bini-params') || '{}');
223
- // params.id โ†’ '123'
224
- return Response.json({ id: params.id });
225
- };
226
- ```
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.
227
247
 
228
- ### CORS
248
+ ### Request limits
229
249
 
230
- CORS is **enabled by default** with these headers:
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.
231
251
 
232
- ```
233
- Access-Control-Allow-Origin: *
234
- Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,OPTIONS,HEAD
235
- Access-Control-Allow-Headers: Content-Type,Authorization,X-Request-ID
236
- ```
252
+ ### When the bundle is missing or broken
237
253
 
238
- Disable with `CORS_ENABLED=false`, `BINI_CORS_ENABLED=false`, or `VITE_CORS_ENABLED=false`.
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"}`.
239
256
 
240
257
  ---
241
258
 
242
- ## ๐Ÿ—‚๏ธ Static File Serving
259
+ ## Static File Serving
243
260
 
244
- ### Supported MIME Types
261
+ ### Lookup order
245
262
 
246
- All common file types are served with correct MIME types:
247
- - HTML, CSS, JavaScript, JSON
248
- - Images: PNG, JPEG, GIF, SVG, WebP, AVIF, ICO
249
- - Fonts: WOFF, WOFF2, TTF, EOT
250
- - Documents: TXT, XML
251
- - Web manifests
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`.
252
264
 
253
- ### Cache Headers
265
+ For a path **without** an extension, the server uses the first of these that applies:
254
266
 
255
- | File Type | Cache Policy |
256
- |-----------|--------------|
257
- | **Assets** (`/assets/*`) | `public, max-age=31536000, immutable` (1 year) |
258
- | **All other files** | `no-cache` |
267
+ | Order | Looks for | Status |
268
+ | --- | --- | --- |
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 |
259
274
 
260
- ### ETag Support
275
+ When `BASE` is set, only paths under it are served; other paths get the plain-text `404 Not found`.
261
276
 
262
- Automatically generates ETags from file `size + mtimeMs`:
263
- - Sends `ETag` header on first request
264
- - Handles `If-None-Match` for `304 Not Modified` responses
265
- - Uses MD5 hash (16 chars) for efficient caching
277
+ ### Shell pages
266
278
 
267
- ---
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.
280
+
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) |
268
286
 
269
- ## ๐Ÿšข Deployment
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.
270
288
 
271
- ### Important: Ship Your `src/` Folder
289
+ ### Supported MIME Types
272
290
 
273
- bini-server runs API handlers directly from `src/app/api/` โ€” they are **not** compiled into `dist/`. When deploying, ensure your server has access to both `dist/` and `src/app/api/`.
291
+ | Extensions | Content-Type |
292
+ | --- | --- |
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`.
274
313
 
275
- - โœ… **VPS/pm2**: Deploy the full project directory
276
- - โœ… **Railway/Render/Fly.io**: Automatic (clones your repository)
277
- - โœ… **Docker**: Copy both `dist/` and `src/` directories
314
+ ### Cache Headers
278
315
 
279
- ### VPS / Dedicated Server
316
+ | File Type | Cache Policy |
317
+ | --- | --- |
318
+ | **Files whose absolute path contains an `assets` folder** | `public, max-age=31536000, immutable` (1 year) |
319
+ | **All other files** | `no-cache` |
280
320
 
281
- ```bash
282
- npm run build
283
- npm start
284
-
285
- # With pm2 (recommended)
286
- npm install -g pm2
287
- pm2 start "npm start" --name my-app
288
- pm2 save
289
- pm2 startup
290
- ```
321
+ The `assets` check is made on the full absolute file path, not only the part inside `dist/`.
291
322
 
292
- ### Platform as a Service
293
-
294
- | Platform | Start Command | Notes |
295
- |----------|---------------|-------|
296
- | **Railway** | `npm start` | PORT injected automatically |
297
- | **Render** | `npm start` | PORT injected automatically |
298
- | **Fly.io** | `npm start` | See fly.toml example below |
299
- | **Heroku** | `npm start` | PORT injected automatically |
300
-
301
- ### Docker
302
-
303
- ```dockerfile
304
- FROM node:20-alpine
305
- WORKDIR /app
306
- COPY package*.json ./
307
- RUN npm install --production
308
- COPY . .
309
- RUN npm run build
310
- EXPOSE 3000
311
- CMD ["npm", "start"]
312
- ```
323
+ ### ETag Support
313
324
 
314
- ### Fly.io
325
+ ETags are generated from the file `size` and `mtimeMs`:
315
326
 
316
- ```toml
317
- # fly.toml
318
- [processes]
319
- app = "npm start"
320
- ```
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.
329
+
330
+ bini-server does not compress responses.
321
331
 
322
332
  ---
323
333
 
324
- ## ๐Ÿ”ง vs `vite preview`
325
-
326
- | Feature | `vite preview` | `bini-server` |
327
- |---------|---------------|---------------|
328
- | Serves `dist/` | โœ… | โœ… |
329
- | API routes | โœ… | โœ… |
330
- | SPA fallback | โœ… | โœ… |
331
- | Auto env loading | โœ… | โœ… |
332
- | ETag / 304 support | โŒ | โœ… |
333
- | Body timeout | โŒ | โœ… (30s) |
334
- | Body size limit | โŒ | โœ… (10MB) |
335
- | Handler timeout | โŒ | โœ… (30s) |
336
- | Graceful shutdown | โŒ | โœ… |
337
- | Module cache | โŒ | โœ… |
338
- | Configurable dirs | โŒ | โœ… |
339
- | CORS control | โŒ | โœ… |
340
- | Zero dependencies | โŒ | โœ… |
341
- | Production use | โš ๏ธ Not recommended | โœ… Production-ready |
334
+ ## Deployment Notes
335
+
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.
342
342
 
343
343
  ---
344
344
 
345
- ## ๐Ÿ›ก๏ธ Security
345
+ ## Security
346
346
 
347
- | Feature | Default | Configurable |
348
- |---------|---------|--------------|
349
- | CORS | Enabled | โœ… via `CORS_ENABLED` |
350
- | Body size limit | 10MB | โœ… via `BODY_SIZE_LIMIT` |
351
- | Request timeout | 30s | โœ… via `BODY_TIMEOUT_SECS` |
352
- | Handler timeout | 30s | โœ… via `HANDLER_TIMEOUT_SECS` |
353
- | Path traversal | Blocked | โœ… (guard in place) |
347
+ | Feature | Default | Configured with |
348
+ | --- | --- | --- |
349
+ | Body size limit (API) | 10 MB | `BODY_SIZE_LIMIT` |
350
+ | Body read timeout (API) | 30 s | `BODY_TIMEOUT_SECS` |
351
+ | 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 |
354
+ | Error messages | `500` responses hide the message when `NODE_ENV=production` | `NODE_ENV` |
355
+ | CORS | Not handled by bini-server | n/a |
354
356
 
355
357
  ---
356
358
 
357
- ## ๐Ÿงช Testing Your Server
359
+ ## Verifying the Server
358
360
 
359
361
  ```bash
360
362
  # Check static files
361
363
  curl http://localhost:3000/
362
364
 
363
- # Check API routes
365
+ # Check an API route (if your API bundle handles it)
364
366
  curl http://localhost:3000/api/hello
365
367
 
366
- # Check ETag
367
- curl -I http://localhost:3000/styles.css
368
+ # Check ETag (use a file that exists in dist/)
369
+ curl -I http://localhost:3000/assets/app.js
368
370
 
369
371
  # Test 304 Not Modified
370
- curl -I http://localhost:3000/styles.css \
372
+ curl -I http://localhost:3000/assets/app.js \
371
373
  -H "If-None-Match: [etag_from_previous_request]"
372
-
373
- # Test CORS
374
- curl -X OPTIONS http://localhost:3000/api/hello \
375
- -H "Origin: http://example.com"
376
374
  ```
377
375
 
378
376
  ---
379
377
 
380
- ## โš™๏ธ Configuration Examples
378
+ ## Configuration Examples
381
379
 
382
- ### Development (All security disabled)
383
- ```bash
384
- CORS_ENABLED=true
385
- BODY_TIMEOUT_SECS=0
386
- HANDLER_TIMEOUT_SECS=0
387
- BODY_SIZE_LIMIT=0
388
- NODE_ENV=development
389
- ```
380
+ ### Production
390
381
 
391
- ### Production (Secure defaults)
392
382
  ```bash
393
- CORS_ENABLED=true
383
+ NODE_ENV=production
384
+ PORT=3000
394
385
  BODY_TIMEOUT_SECS=30
395
386
  HANDLER_TIMEOUT_SECS=30
396
387
  BODY_SIZE_LIMIT=10485760
397
- NODE_ENV=production
398
388
  ```
399
389
 
400
- ### Internal API (No CORS)
390
+ ### Served under a sub-path
391
+
392
+ ```bash
393
+ BASE=/app
394
+ ```
395
+
396
+ ### Smaller request bodies
397
+
401
398
  ```bash
402
- CORS_ENABLED=false
403
- BODY_SIZE_LIMIT=5242880 # 5MB
399
+ BODY_SIZE_LIMIT=1048576 # 1MB
404
400
  ```
405
401
 
406
- ### File Upload Service
402
+ ### Larger uploads
403
+
407
404
  ```bash
408
- CORS_ENABLED=true
409
- BODY_SIZE_LIMIT=1073741824 # 1GB
410
- BODY_TIMEOUT_SECS=300 # 5 minutes
405
+ BODY_SIZE_LIMIT=104857600 # 100MB
406
+ BODY_TIMEOUT_SECS=300 # 5 minutes
411
407
  ```
412
408
 
413
409
  ---
414
410
 
415
- ## ๐Ÿ“š API Reference
411
+ ## API Reference
416
412
 
417
413
  ### Environment Variables Priority
418
414
 
@@ -420,28 +416,32 @@ BODY_TIMEOUT_SECS=300 # 5 minutes
420
416
  2. `VITE_*` (medium)
421
417
  3. No prefix (lowest)
422
418
 
423
- ### Returned HTTP Status Codes
419
+ ### HTTP Status Codes Produced by bini-server
420
+
421
+ API handlers may return any status.
424
422
 
425
423
  | Code | Description |
426
- |------|-------------|
424
+ | --- | --- |
427
425
  | `200` | Success |
428
- | `204` | OPTIONS preflight success |
429
426
  | `304` | Not Modified (ETag match) |
430
- | `400` | Bad Request URL |
431
- | `404` | Route not found |
432
- | `408` | Request timeout |
433
- | `413` | Payload too large |
434
- | `500` | Internal server error |
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 |
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.
435
+
436
+ With `NODE_ENV=production` the message in `500` responses from handler errors is always `Internal server error`.
435
437
 
436
438
  ### Supported HTTP Methods
437
439
 
438
- - `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
439
- - `OPTIONS` (CORS preflight)
440
- - `HEAD` (with ETag support)
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.
441
441
 
442
442
  ---
443
443
 
444
- ## ๐Ÿค Contributing
444
+ ## Contributing
445
445
 
446
446
  1. Fork the repository
447
447
  2. Create your feature branch
@@ -451,13 +451,13 @@ BODY_TIMEOUT_SECS=300 # 5 minutes
451
451
 
452
452
  ---
453
453
 
454
- ## ๐Ÿ“ License
454
+ ## License
455
455
 
456
456
  MIT ยฉ [Binidu Ranasinghe](https://bini.js.org)
457
457
 
458
458
  ---
459
459
 
460
- ## ๐Ÿ”— Links
460
+ ## Links
461
461
 
462
462
  - [GitHub](https://github.com/Binidu01/bini-server)
463
463
  - [npm](https://www.npmjs.com/package/bini-server)
@@ -466,8 +466,4 @@ MIT ยฉ [Binidu Ranasinghe](https://bini.js.org)
466
466
 
467
467
  ---
468
468
 
469
- <div align="center">
470
-
471
- **Built with โค๏ธ by [Binidu Ranasinghe](https://github.com/Binidu01)**
472
-
473
- </div>
469
+ Maintained by [Binidu Ranasinghe](https://github.com/Binidu01)