bini-server 1.0.10 โ†’ 2.0.1

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,76 @@
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
5
  [![node](https://img.shields.io/badge/node-%3E%3D20-339933?style=flat-square&logo=nodedotjs&logoColor=white&labelColor=0a0a0a)](https://nodejs.org)
8
6
  [![bundle size](https://img.shields.io/bundlephobia/min/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://bundlephobia.com/package/bini-server)
9
7
  [![downloads](https://img.shields.io/npm/dt/bini-server?style=flat-square&logo=npm&labelColor=0a0a0a)](https://www.npmjs.com/package/bini-server)
10
8
 
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.
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.
11
+
12
+ ---
13
13
 
14
- </div>
14
+ ## Table of Contents
15
+
16
+ - [Features](#features)
17
+ - [Requirements](#requirements)
18
+ - [Install](#install)
19
+ - [Usage](#usage)
20
+ - [Keyboard Shortcuts](#keyboard-shortcuts)
21
+ - [Environment Variables](#environment-variables)
22
+ - [Project Structure](#project-structure)
23
+ - [API Routes](#api-routes)
24
+ - [Static File Serving](#static-file-serving)
25
+ - [Deployment](#deployment)
26
+ - [Security](#security)
27
+ - [Verifying the Server](#verifying-the-server)
28
+ - [Configuration Examples](#configuration-examples)
29
+ - [API Reference](#api-reference)
30
+ - [Contributing](#contributing)
31
+ - [License](#license)
15
32
 
16
33
  ---
17
34
 
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
35
+ ## Features
36
+
37
+ ### Core
38
+
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.
43
+ - **Sub-path deployments.** Serve the app under a `BASE` path.
44
+
45
+ ### Security and Reliability
46
+
47
+ - **Body limits.** Configurable request body size limit for API requests (default 10 MB).
48
+ - **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.
52
+
53
+ ### Operations
54
+
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.
59
+ - **Flexible config.** Supports `BINI_*`, `VITE_*`, or unprefixed environment variables.
42
60
 
43
61
  ---
44
62
 
45
- ## ๐Ÿ“‹ Requirements
63
+ ## Requirements
46
64
 
47
65
  - 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)
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)
50
70
 
51
71
  ---
52
72
 
53
- ## ๐Ÿ“ฆ Install
73
+ ## Install
54
74
 
55
75
  ```bash
56
76
  npm install bini-server
@@ -62,7 +82,7 @@ yarn add bini-server
62
82
 
63
83
  ---
64
84
 
65
- ## ๐Ÿš€ Usage
85
+ ## Usage
66
86
 
67
87
  ### 1. Add to `package.json`
68
88
 
@@ -84,92 +104,130 @@ npm start # Serve in production
84
104
 
85
105
  ### 3. Terminal Output
86
106
 
87
- ```
88
- รŸ Bini.js (production)
89
- โžœ Environments: .env, .env.local
107
+ ```text
108
+ รŸ Bini.js (production)
109
+ โžœ Environments: .env.local, .env
90
110
  โžœ Local: http://localhost:3000/
91
111
  โžœ Network: http://192.168.1.5:3000/
92
112
  โžœ press h + enter to show help
93
113
  ```
94
114
 
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.
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 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.
137
+
95
138
  ---
96
139
 
97
- ## โŒจ๏ธ Keyboard Shortcuts
140
+ ## Keyboard Shortcuts
98
141
 
99
142
  While the server is running, type a key and press `enter`:
100
143
 
101
144
  | Key | Action |
102
- |-----|--------|
145
+ | --- | --- |
103
146
  | `h` | Show available shortcuts |
104
- | `o` | Open your app in the default browser |
147
+ | `o` | Open `http://localhost:<port><base>/` in the default browser |
105
148
  | `q` | Quit the server |
106
149
 
107
- > Keyboard shortcuts are automatically disabled in non-interactive environments (like Render, CI/CD).
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.
108
151
 
109
152
  ---
110
153
 
111
- ## ๐ŸŒฟ Environment Variables
154
+ ## Environment Variables
112
155
 
113
- ### Auto-Detected `.env` Files
156
+ ### `.env` Files
114
157
 
115
- At startup, bini-server automatically detects and loads:
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):
116
159
 
117
- 1. `.env.local`
118
- 2. `.env.[NODE_ENV].local` (e.g., `.env.production.local`)
119
- 3. `.env.[NODE_ENV]` (e.g., `.env.production`)
160
+ 1. `.env.[mode].local`
161
+ 2. `.env.[mode]`
162
+ 3. `.env.local`
120
163
  4. `.env`
121
164
 
122
- All detected files are listed in the startup banner.
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.
123
166
 
124
167
  ### Server Configuration
125
168
 
126
- All environment variables support **three naming conventions:**
169
+ All settings support **three naming conventions:**
127
170
 
128
171
  | Convention | Example | Priority |
129
- |------------|---------|----------|
172
+ | --- | --- | --- |
130
173
  | `BINI_*` | `BINI_PORT=3000` | Highest |
131
174
  | `VITE_*` | `VITE_PORT=3000` | Medium |
132
175
  | No prefix | `PORT=3000` | Lowest |
133
176
 
134
177
  | 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) |
178
+ | --- | --- | --- |
179
+ | `PORT` | `3000` | HTTP port to listen on. If it is in use, the next free port is used (see [Port selection](#port-selection)) |
180
+ | `DIST_DIR` | `dist` | Build output folder, relative to the working directory |
181
+ | `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
+ | `BODY_TIMEOUT_SECS` | `30` | Max seconds to read an API request body |
183
+ | `HANDLER_TIMEOUT_SECS` | `30` | Max seconds for the API handler to respond |
184
+ | `BODY_SIZE_LIMIT` | `10485760` | Max API request body size in bytes (10 MB) |
185
+
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.
187
+
188
+ The server also reads `NODE_ENV`. When it is `production`, error responses hide the underlying message.
189
+
190
+ ### Port selection
191
+
192
+ 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:
193
+
194
+ ```text
195
+ Port 3000 is in use, trying another one...
196
+ ```
197
+
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>`.
143
199
 
144
200
  ### Examples
145
201
 
146
202
  ```bash
147
203
  # .env file
148
204
  PORT=8080
149
- CORS_ENABLED=false
150
- API_DIR=src/api
151
205
  BODY_SIZE_LIMIT=5242880 # 5MB
152
206
 
153
207
  # Or inline
154
- PORT=3001 BINI_CORS_ENABLED=false bini-server
208
+ PORT=3001 bini-server
155
209
 
156
- # Or with VITE prefix
157
- VITE_PORT=3000 VITE_CORS_ENABLED=false bini-server
210
+ # Or with the BINI prefix (takes precedence over PORT)
211
+ BINI_PORT=3002 bini-server
158
212
  ```
159
213
 
160
214
  ---
161
215
 
162
- ## ๐Ÿ“ Project Structure
216
+ ## Project Structure
163
217
 
164
- ```
218
+ ```text
165
219
  my-app/
166
- โ”œโ”€โ”€ dist/ # Built static files (required)
220
+ โ”œโ”€โ”€ dist/ # Built output (required)
167
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
168
225
  โ”‚ โ”œโ”€โ”€ assets/
169
- โ”‚ โ””โ”€โ”€ ...
226
+ โ”‚ โ””โ”€โ”€ api/
227
+ โ”‚ โ””โ”€โ”€ index.mjs # Compiled API bundle (not served as a file)
170
228
  โ”œโ”€โ”€ src/
171
229
  โ”‚ โ”œโ”€โ”€ app/
172
- โ”‚ โ”‚ โ”œโ”€โ”€ api/ # API handlers (optional)
230
+ โ”‚ โ”‚ โ”œโ”€โ”€ api/ # API handlers, compiled into dist/api at build time
173
231
  โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ users.ts
174
232
  โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ posts/
175
233
  โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ index.ts
@@ -183,98 +241,143 @@ my-app/
183
241
 
184
242
  ---
185
243
 
186
- ## ๐ŸŒ API Routes
244
+ ## API Routes
187
245
 
188
- ### Supported Formats
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.
189
247
 
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;
196
-
197
- // 2. Plain Function
198
- export default (req: Request) => {
199
- return Response.json({ message: 'Hello' });
200
- };
248
+ ### What the bundle receives
249
+
250
+ ```ts
251
+ fetch(request: Request, env: NodeJS.ProcessEnv, ctx: { waitUntil(p: Promise<unknown>): void })
201
252
  ```
202
253
 
203
- ### Supported Extensions
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.
256
+ - **`ctx.waitUntil`:** accepts a promise and swallows its rejection; the server does not wait for it.
204
257
 
205
- Only `.ts` and `.js` files are supported for API routes (Next.js convention).
258
+ 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
259
 
207
- ### Dynamic Routes
260
+ ### Supported handler formats
208
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
+ }
209
280
  ```
281
+
282
+ Only `.ts` and `.js` files in `src/app/api/` are used.
283
+
284
+ ### Dynamic routes
285
+
286
+ ```text
210
287
  src/app/api/
211
288
  users/
212
- [id].ts โ†’ /api/users/:id
289
+ [id].ts โ†’ /api/users/:id
213
290
  posts/
214
- [...slug].ts โ†’ /api/posts/*
291
+ [...slug].ts โ†’ /api/posts/*
215
292
  ```
216
293
 
217
- ### Route Parameters
218
-
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
- ```
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.
227
295
 
228
296
  ### CORS
229
297
 
230
- CORS is **enabled by default** with these headers:
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).
231
299
 
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
- ```
300
+ ### Base path
301
+
302
+ bini-server and the compiled API each check the base path, so set `BASE` to the sub-path your app was built for.
303
+
304
+ ### Request limits
237
305
 
238
- Disable with `CORS_ENABLED=false`, `BINI_CORS_ENABLED=false`, or `VITE_CORS_ENABLED=false`.
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.
307
+
308
+ ### When the bundle is missing
309
+
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"}`.
239
311
 
240
312
  ---
241
313
 
242
- ## ๐Ÿ—‚๏ธ Static File Serving
314
+ ## Static File Serving
315
+
316
+ ### Lookup order
317
+
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`.
319
+
320
+ For a path **without** an extension, the server uses the first of these that applies:
321
+
322
+ | Order | Looks for | Status |
323
+ | --- | --- | --- |
324
+ | 1 | `dist/<path>/index.html` (pre-rendered page) | 200 |
325
+ | 2 | A shell page whose folder name matches the path | 200 |
326
+ | 3 | `dist/404.html` | 404 |
327
+ | 4 | `dist/index.html` (client-side fallback) | 200 |
328
+ | 5 | Nothing found | plain-text 404 |
329
+
330
+ When `BASE` is set, only paths under it are served.
331
+
332
+ ### Shell pages
333
+
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.
335
+
336
+ | Folder | Matches |
337
+ | --- | --- |
338
+ | `blog/[slug]` | `/blog/anything` (exactly one segment in that position) |
339
+ | `docs/[...path]` | `/docs/a`, `/docs/a/b` (at least one segment) |
340
+ | `docs/[[...path]]` | `/docs`, `/docs/a`, `/docs/a/b` (zero or more segments) |
341
+
342
+ Bracketed segments match any value, other segments must match exactly, and the first matching shell wins; there is no ranking by specificity.
243
343
 
244
344
  ### Supported MIME Types
245
345
 
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
346
+ | Type | Extensions |
347
+ | --- | --- |
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`.
252
353
 
253
354
  ### Cache Headers
254
355
 
255
356
  | File Type | Cache Policy |
256
- |-----------|--------------|
257
- | **Assets** (`/assets/*`) | `public, max-age=31536000, immutable` (1 year) |
357
+ | --- | --- |
358
+ | **Files inside an `assets/` folder** | `public, max-age=31536000, immutable` (1 year) |
258
359
  | **All other files** | `no-cache` |
259
360
 
260
361
  ### ETag Support
261
362
 
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
363
+ ETags are generated from the file `size` and `mtimeMs`:
364
+
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).
367
+
368
+ bini-server does not compress responses.
266
369
 
267
370
  ---
268
371
 
269
- ## ๐Ÿšข Deployment
372
+ ## Deployment
270
373
 
271
- ### Important: Ship Your `src/` Folder
374
+ ### What to ship
272
375
 
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/`.
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.
274
377
 
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
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
278
381
 
279
382
  ### VPS / Dedicated Server
280
383
 
@@ -292,10 +395,10 @@ pm2 startup
292
395
  ### Platform as a Service
293
396
 
294
397
  | Platform | Start Command | Notes |
295
- |----------|---------------|-------|
398
+ | --- | --- | --- |
296
399
  | **Railway** | `npm start` | PORT injected automatically |
297
400
  | **Render** | `npm start` | PORT injected automatically |
298
- | **Fly.io** | `npm start` | See fly.toml example below |
401
+ | **Fly.io** | `npm start` | See the fly.toml example below |
299
402
  | **Heroku** | `npm start` | PORT injected automatically |
300
403
 
301
404
  ### Docker
@@ -304,9 +407,10 @@ pm2 startup
304
407
  FROM node:20-alpine
305
408
  WORKDIR /app
306
409
  COPY package*.json ./
307
- RUN npm install --production
410
+ RUN npm ci
308
411
  COPY . .
309
- RUN npm run build
412
+ RUN npm run build && npm prune --omit=dev
413
+ ENV NODE_ENV=production
310
414
  EXPOSE 3000
311
415
  CMD ["npm", "start"]
312
416
  ```
@@ -321,40 +425,21 @@ CMD ["npm", "start"]
321
425
 
322
426
  ---
323
427
 
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 |
428
+ ## Security
342
429
 
343
- ---
344
-
345
- ## ๐Ÿ›ก๏ธ Security
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) |
430
+ | Feature | Default | Configured with |
431
+ | --- | --- | --- |
432
+ | Body size limit (API) | 10 MB | `BODY_SIZE_LIMIT` |
433
+ | Body read timeout (API) | 30 s | `BODY_TIMEOUT_SECS` |
434
+ | Handler timeout (API) | 30 s | `HANDLER_TIMEOUT_SECS` |
435
+ | Path traversal | `..` segments and null bytes are not served | Not configurable |
436
+ | 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
439
 
355
440
  ---
356
441
 
357
- ## ๐Ÿงช Testing Your Server
442
+ ## Verifying the Server
358
443
 
359
444
  ```bash
360
445
  # Check static files
@@ -364,55 +449,51 @@ curl http://localhost:3000/
364
449
  curl http://localhost:3000/api/hello
365
450
 
366
451
  # Check ETag
367
- curl -I http://localhost:3000/styles.css
452
+ curl -I http://localhost:3000/assets/app.js
368
453
 
369
454
  # Test 304 Not Modified
370
- curl -I http://localhost:3000/styles.css \
455
+ curl -I http://localhost:3000/assets/app.js \
371
456
  -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
457
  ```
377
458
 
378
459
  ---
379
460
 
380
- ## โš™๏ธ Configuration Examples
461
+ ## Configuration Examples
381
462
 
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
- ```
463
+ ### Production
390
464
 
391
- ### Production (Secure defaults)
392
465
  ```bash
393
- CORS_ENABLED=true
466
+ NODE_ENV=production
467
+ PORT=3000
394
468
  BODY_TIMEOUT_SECS=30
395
469
  HANDLER_TIMEOUT_SECS=30
396
470
  BODY_SIZE_LIMIT=10485760
397
- NODE_ENV=production
398
471
  ```
399
472
 
400
- ### Internal API (No CORS)
473
+ ### Served under a sub-path
474
+
401
475
  ```bash
402
- CORS_ENABLED=false
403
- BODY_SIZE_LIMIT=5242880 # 5MB
476
+ BASE=/app
404
477
  ```
405
478
 
406
- ### File Upload Service
479
+ ### Smaller request bodies
480
+
407
481
  ```bash
408
- CORS_ENABLED=true
409
- BODY_SIZE_LIMIT=1073741824 # 1GB
410
- BODY_TIMEOUT_SECS=300 # 5 minutes
482
+ BODY_SIZE_LIMIT=1048576 # 1MB
411
483
  ```
412
484
 
485
+ ### Larger uploads
486
+
487
+ ```bash
488
+ BODY_SIZE_LIMIT=104857600 # 100MB
489
+ BODY_TIMEOUT_SECS=300 # 5 minutes
490
+ ```
491
+
492
+ Raise `bodySizeLimit` in `biniroute()` too, otherwise the bundle's own limit still applies.
493
+
413
494
  ---
414
495
 
415
- ## ๐Ÿ“š API Reference
496
+ ## API Reference
416
497
 
417
498
  ### Environment Variables Priority
418
499
 
@@ -422,26 +503,27 @@ BODY_TIMEOUT_SECS=300 # 5 minutes
422
503
 
423
504
  ### Returned HTTP Status Codes
424
505
 
506
+ These are produced by bini-server itself. API handlers may return any status.
507
+
425
508
  | Code | Description |
426
- |------|-------------|
509
+ | --- | --- |
427
510
  | `200` | Success |
428
- | `204` | OPTIONS preflight success |
429
511
  | `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 |
512
+ | `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) |
517
+
518
+ In production (`NODE_ENV=production`) the message in `500` responses is always `Internal server error`.
435
519
 
436
520
  ### Supported HTTP Methods
437
521
 
438
- - `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
439
- - `OPTIONS` (CORS preflight)
440
- - `HEAD` (with ETag support)
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.
441
523
 
442
524
  ---
443
525
 
444
- ## ๐Ÿค Contributing
526
+ ## Contributing
445
527
 
446
528
  1. Fork the repository
447
529
  2. Create your feature branch
@@ -451,13 +533,13 @@ BODY_TIMEOUT_SECS=300 # 5 minutes
451
533
 
452
534
  ---
453
535
 
454
- ## ๐Ÿ“ License
536
+ ## License
455
537
 
456
538
  MIT ยฉ [Binidu Ranasinghe](https://bini.js.org)
457
539
 
458
540
  ---
459
541
 
460
- ## ๐Ÿ”— Links
542
+ ## Links
461
543
 
462
544
  - [GitHub](https://github.com/Binidu01/bini-server)
463
545
  - [npm](https://www.npmjs.com/package/bini-server)
@@ -466,8 +548,4 @@ MIT ยฉ [Binidu Ranasinghe](https://bini.js.org)
466
548
 
467
549
  ---
468
550
 
469
- <div align="center">
470
-
471
- **Built with โค๏ธ by [Binidu Ranasinghe](https://github.com/Binidu01)**
472
-
473
- </div>
551
+ Maintained by [Binidu Ranasinghe](https://github.com/Binidu01)