### Example: disable/enable settings
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Example usage of `disable`, `enabled`, `disabled`, and `enable` methods on an app instance.
```js
app.disable("x-powered-by");
console.log(app.enabled("x-powered-by")); // false
console.log(app.disabled("x-powered-by")); // true
app.enable("catch async errors");
```
--------------------------------
### Plain HTTP example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Example of creating a plain HTTP server with ultimate-express. The app uses uWS.App by default. It defines a GET route and starts listening on port 3000.
```javascript
const express = require("ultimate-express");
const app = express(); // uWS.App
app.get("/", (req, res) => res.send("hello"));
app.listen(3000, () => console.log("up"));
```
--------------------------------
### listen example: TCP port with host
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Shows basic usage of listen with a port and host, and a callback that logs when listening.
```javascript
const app = express();
app.get("/", (req, res) => res.send("ok"));
app.listen(3000, "localhost", () => console.log("listening on 3000"));
```
--------------------------------
### HTTPS example with uwsOptions
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Example of creating an HTTPS server by passing key and certificate file names to uwsOptions. This uses uWS.SSLApp instead of Node's https.createServer. The app listens on port 3000.
```javascript
const express = require("ultimate-express");
const app = express({
uwsOptions: {
key_file_name: "server.key",
cert_file_name: "server.crt",
},
});
app.listen(3000);
```
--------------------------------
### engine(ext, fn) usage example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Shows how to set up a Pug view engine and render a template. Uses app.engine, app.set, and app.get.
```javascript
const app = express();
app.engine("pug", require("pug").__express);
app.set("view engine", "pug");
app.get("/", (req, res) => res.render("index"));
```
--------------------------------
### listen(port, host, callback)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Starts the HTTP server on the specified port and host, or on a Unix socket. Supports multiple overloads and returns the Application instance for chaining.
```APIDOC
## [LISTEN] listen(port, host, callback)
### Description
Starts the HTTP server on the specified port and host, or on a Unix socket. Supports multiple overloads and returns the Application instance for chaining.
### Method
LISTEN
### Endpoint
listen(port, host, callback)
### Parameters
#### Path Parameters
- **port** (number | string | function) - Required - TCP port (number or numeric string) or Unix socket path; port `0` = ephemeral port. When called as `listen(callback)`, defaults to `0`.
- **host** (string | function) - Optional - Interface to bind; a function here is treated as `callback`.
- **callback** (function) - Optional - Invoked (no arguments) once uWS reports the socket is listening; note it is called as `callback()`, not Express's `token` signature.
### Request Example
```js
const app = express();
app.get("/", (req, res) => res.send("ok"));
app.listen(3000, "localhost", () => console.log("listening on 3000"));
```
### Response
#### Success Response (200)
- **this** (Application) - The Application instance, allowing chaining.
#### Response Example
```js
const server = app.listen(0); // ephemeral port
console.log(server.address().port); // actual port assigned by the OS
```
### Error Handling
- **EADDRINUSE** - Thrown in the onListen callback if the port is already in use. Error message: `listen EADDRINUSE: address already in use :::' + port` with `err.code = 'EADDRINUSE'`.
### Overloads
- `listen(callback)` - Port defaults to `0` (kernel-assigned), callback invoked on success
- `listen(port, callback)` - Numeric port
- `listen(port)` - No callback
- `listen(port, host, callback)` - Host bind (e.g. `'localhost'`)
- `listen(port, host)` - No callback
- `listen(unixSocketPath[, callback])` - Non-numeric, non-numeric-string arg switches to `uwsApp.listen_unix`; the socket path is passed through
```
--------------------------------
### Install ultimate-express via npm
Source: https://github.com/dimdengd/ultimate-express/blob/main/README.md
Install the latest version of ultimate-express. Replace 'express' with 'ultimate-express' in your project. Use 'npm install ultimate-express@2.1.0' for Node.js v21, v20, and v19, or 'npm install ultimate-express@node-v18' for Node.js v18.
```bash
npm install ultimate-express
```
```bash
npm install ultimate-express@2.1.0
```
```bash
npm install ultimate-express@node-v18
```
--------------------------------
### render(name, options, callback) usage example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Shows rendering a view with locals and passing data. Uses app.set, app.locals, and app.get.
```javascript
const app = express();
app.set("view engine", "pug");
app.locals.title = "My App";
app.get("/", (req, res) => res.render("index", { message: "hi" }));
```
--------------------------------
### address example: ephemeral port
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Shows how to get the actual port assigned by the OS when listening on port 0.
```javascript
const server = app.listen(0); // ephemeral port
console.log(server.address().port); // actual port assigned by the OS
```
--------------------------------
### Instantiate View and render with callback
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/view.md
Example equivalent to what app.render does internally. Instantiates the View class with the app's view engine, views root, and engines, then renders a template with a callback.
```js
const View = app.get('view');
const view = new View('index', {
defaultEngine: app.get('view engine'), // 'pug'
root: app.get('views'), // path.resolve('views')
engines: { ...app.engines },
});
view.render({ title: 'hi' }, (err, html) => { /* ... */ });
```
--------------------------------
### path example: mounted sub-app
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Shows that path() returns the mount path of a sub-app mounted under '/abc'.
```javascript
const app = express();
const sub = express();
app.use("/abc", sub);
sub.listen(3000);
console.log(sub.path()); // "/abc"
```
--------------------------------
### Using req.accepts for content negotiation
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/request.md
Example usage of `req.accepts` to negotiate content types. Returns the best match or `false`; the example responds with JSON, HTML, or a 406 status.
```javascript
app.get("/", (req, res) => {
if (req.accepts("json")) return res.json({ hi: "there" });
if (req.accepts("html")) return res.send("
hi
");
res.status(406).end();
});
```
--------------------------------
### close(callback) usage example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Shows closing the server after a delay. Uses app.listen and server.close.
```javascript
const server = app.listen(3000);
setTimeout(() => server.close(() => console.log("closed")), 1000);
```
--------------------------------
### Setting app settings
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/configuration.md
Examples of setting various app settings. Note that setting 'env' to 'production' also enables 'view cache', and 'trust proxy' accepts a number to trust that many proxy hops.
```javascript
app.set('env', 'production');
app.set('view engine', 'pug');
app.set('trust proxy', 1); // trust one proxy hop
app.set('query parser', 'extended');
app.set('etag', 'strong');
app.disable('x-powered-by');
app.enable('catch async errors');
app.set('body methods', ['GET']);
```
--------------------------------
### Router HTTP methods
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Documentation for the HTTP method route registration methods installed on the Router constructor.
```APIDOC
## Router Methods
### Description
Each HTTP method (e.g., `post`, `put`, `delete`, `patch`, `options`, `head`, `trace`, `connect`, and others) is installed as a method on the Router instance. Each method registers a route for the given path with the provided callbacks.
### Method
Various (see list)
### Endpoint
router.M(path, ...callbacks)
### Parameters
#### Path Parameters
- **path** (string) - Required - The route path.
- **callbacks** (function|array) - Required - One or more callback functions or arrays of functions to handle the route.
### Returns
- **Router** - The Router instance (for chaining).
### Example
```js
router.post('/users', (req, res) => { /* ... */ });
```
```
--------------------------------
### Example: using app.param with a route
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Shows how to use `app.param` to intercept a parameter value and conditionally send a response, then define a route that uses that parameter. The callback receives `(req, res, next, id)` and calls `next()` to continue.
```javascript
app.param('id', (req, res, next, id) => {
if (id === '555') return res.send('blocked');
next();
});
app.get('/user/:id', (req, res) => res.send(`user ${req.params.id}`));
```
--------------------------------
### get(path, ...callbacks)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Registers a GET route handler or acts as a settings getter when called with a single string argument. Supports path patterns and arrays, and returns the router or route handle.
```APIDOC
## GET [path]
### Description
Registers a GET route handler for the given path, or retrieves a setting value when called with a single string argument (Express compatibility).
### Method
GET
### Endpoint
[path]
### Parameters
#### Path Parameters
- **path** (string | RegExp | string[]) - Required - Route path; arrays register one route per entry; '*' is normalized to '/*'; trailing slashes are stripped when strict routing is off.
#### Query Parameters
- **callbacks** (Handler[] | Router[]) - Required - Middleware/handler chain; Router instances are mounted and dispatched.
### Request Example
```js
app.get('/users/:id', (req, res) => { ... });
```
### Response
#### Success Response (200)
- **parent** (Router) - The router itself (this) or the route-handle object for route()-created chains.
#### Response Example
```js
// Returns the router instance for chaining
```
```
--------------------------------
### listen example: Unix socket and error surface
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Shows listening on a Unix socket and demonstrates that a bind failure raises an EADDRINUSE error in the onListen callback rather than returning it.
```javascript
const app = express();
app.listen("/tmp/app.sock", () => console.log("unix socket up"));
// listen failure removes availability; if the port is taken, the EADDRINUSE
// error is raised in the onListen callback rather than returned:
app.listen(80, () => {});
```
--------------------------------
### Type-usage example with RequestHandler and Router
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/types.md
Shows how to use the exported types and the callable module: create an app with `threads: 2`, define a typed `RequestHandler`, use a generic route with `req.params.id` typed as `string`, mount a router, and listen on port 3000. The callback logs whether `app.uwsApp` is defined.
```ts
import express, { Router } from 'ultimate-express';
import type { Request, Response, NextFunction, RequestHandler } from 'ultimate-express';
const app = express({ threads: 2 });
const api = express.Router();
const handler: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
res.json({ path: req.path });
};
api.get<{ id: string }>('/users/:id', (req, res) => {
req.params.id; // string
res.send('ok');
});
app.use('/api', api);
app.listen(3000, () => console.log(app.uwsApp !== undefined));
```
--------------------------------
### Chaining GET and POST handlers with app.route
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Demonstrates chaining multiple HTTP method handlers on a single path using `app.route`. Each method call registers a route for the shared path.
```javascript
app.route("/book")
.get((req, res) => res.send("get a random book"))
.post((req, res) => res.send("add a book"));
```
--------------------------------
### Using express.static with options
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/middlewares.md
Example usage of express.static. The first call serves the 'public' directory with caching options (maxAge, immutable) and a custom index file. The second call mounts static serving for '/assets' with fallthrough disabled, so missing files will not call next().
```javascript
const express = require("ultimate-express");
const app = express();
app.use(express.static("public", {
maxAge: "1d",
immutable: true,
index: "index.html",
}));
// single-file option
app.use("/assets", express.static("public/assets", { fallthrough: false }));
```
--------------------------------
### express.raw usage example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/middlewares.md
Example usage of `express.raw` with a custom `type` and `limit`. The `req.body` is a `Buffer` containing the raw bytes.
```js
app.use(express.raw({ type: "application/x-binary", limit: "10kb" }));
app.post("/blob", (req, res) => {
res.send(Buffer.byteLength(req.body)); // raw bytes available as Buffer
});
```
--------------------------------
### Run a single benchmark scenario
Source: https://github.com/dimdengd/ultimate-express/blob/main/benchmark/README.md
Runs a single benchmark scenario for the duration of 20 seconds. Replace hello-world with any scenario from the list.
```bash
npm run benchmark:compare -- --duration 20 --scenario hello-world
```
--------------------------------
### get(path, ...callbacks) - GET route registration and settings getter
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Registers a GET route or acts as a settings getter when called with a single string path and no callbacks. When used as a getter, it returns the setting value, searching parent routers if not found locally.
```javascript
// src/router.js:92-103
get(path, ...callbacks) {
if(typeof path === 'string' && callbacks.length === 0) {
const key = path;
const res = this.settings[key];
if(typeof res === 'undefined' && this.parent) {
return this.parent.get(key);
} else {
return res;
}
}
return this.createRoute('GET', path, this, ...callbacks);
}
```
--------------------------------
### Run all benchmark scenarios
Source: https://github.com/dimdengd/ultimate-express/blob/main/benchmark/README.md
Runs all benchmark scenarios for the duration of 20 seconds and outputs a summary to benchmark_summary.md. Use this to compare express vs ultimate-express across all scenarios.
```bash
npm run benchmark:compare -- --duration 20 --output benchmark_summary.md
```
--------------------------------
### get(field) / getHeader(field) / getHeaders()
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/response.md
Retrieves response header values. `get` and `getHeader` are aliases; `getHeaders` returns the entire headers object.
```APIDOC
## `get(field)` / `getHeader(field)` / `getHeaders()`
### Description
Retrieves response header values. `get` and `getHeader` are aliases; `getHeaders` returns the entire headers object.
### Method
`get` / `getHeader` / `getHeaders`
### Parameters
- **field** (string) - Required - Header name (case-insensitive).
### Returns
- `get`/`getHeader`: header value or `undefined`.
- `getHeaders`: the headers object.
```
--------------------------------
### express.json usage example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/middlewares.md
Example usage of `express.json` with `limit` and `strict` options. The `strict: true` option rejects non-object bodies with `Error('Invalid body')`.
```js
const express = require("ultimate-express");
const app = express();
app.use(express.json({ limit: "2mb", strict: true }));
app.post("/users", (req, res) => {
// req.body is the parsed JSON object
res.json({ got: req.body });
});
```
--------------------------------
### express.urlencoded usage example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/middlewares.md
Example usage of express.urlencoded middleware with the 'extended' option set to true. It parses the request body and the route handler responds with the submitted data as JSON.
```javascript
app.use(express.urlencoded({ extended: true }));
app.post("/form", (req, res) => {
res.json({ submitted: req.body });
});
```
--------------------------------
### Mounting a router and adding global middleware with app.use
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Shows how to mount a router on a path and add global middleware using `app.use`. The mounted router's `mountpath` is set to the given path, and the global middleware runs for all requests.
```javascript
const app = express();
const api = express.Router();
api.get("/users/:id", (req, res) => res.json({ id: req.params.id }));
app.use("/api", api); // mounted: api.mountpath === "/api"
app.use((req, res, next) => next()); // global middleware
```
--------------------------------
### express.text usage example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/middlewares.md
Example usage of express.text middleware with a custom type 'text/x-markdown'. It sets req.body to the decoded string, and the route handler sends the length of the received body.
```javascript
app.use(express.text({ type: "text/x-markdown" }));
app.post("/doc", (req, res) => {
res.send(`received ${req.body.length} chars`);
});
```
--------------------------------
### Create Router with options
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/configuration.md
Creates a router with caseSensitive, strict, and mergeParams options enabled, then mounts it at the '/api' path. Options become settings like 'case sensitive routing' and 'strict routing'; additional keys fall through into settings.
```javascript
const router = express.Router({ caseSensitive: true, strict: true, mergeParams: true });
app.use('/api', router);
```
--------------------------------
### get(field) / getHeader(field) / getHeaders()
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/response.md
Retrieves response headers. `get` and `getHeader` return the header value (or `undefined` if not set); `getHeaders` returns the entire headers object.
```javascript
// src/response.js:632-639
get(field) { return this.headers[field.toLowerCase()]; }
getHeader(field) { return this.get(field); }
getHeaders(){ return this.headers; }
```
--------------------------------
### HTTPS server creation with Ultimate Express
Source: https://github.com/dimdengd/ultimate-express/blob/main/README.md
Shows the recommended way to create an HTTPS server with Ultimate Express by passing 'uwsOptions' to the 'express()' constructor and using 'app.listen()'. This approach is required instead of manually creating the server.
```javascript
const express = require("ultimate-express");
const app = express({
uwsOptions: {
// https://unetworking.github.io/uWebSockets.js/generated/interfaces/AppOptions.html
key_file_name: 'path/to/key.pem',
cert_file_name: 'path/to/cert.pem'
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
--------------------------------
### render error path example
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/view.md
Example error path for `render`: sets the view engine to EJS and renders a missing template, passing errors to the error pipeline via `next(err)`.
```javascript
const app = express();
app.set('view engine', 'ejs');
app.get('/', (req, res, next) => {
res.render('missing-template', {}, (err, html) => {
if (err) return next(err); // render errors flow into the error pipeline
res.send(html);
});
});
```
--------------------------------
### download(path, filename, options, callback)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/response.md
Documentation for the `download` method of the response object.
```APIDOC
## `download(path, filename, options, callback)`
### Description
Initiates a file download by setting the `Content-Disposition` attachment header and then delegating to `sendFile`. If no root is given and `path` is relative, `opts.root = process.cwd()`.
### Method
`download`
### Parameters
- `path` (string) - Required - File path
- `filename` (string | object | function) - Optional - Download name; an object here is treated as options; a function as callback
- `options` (object | function) - Optional - sendFile options, or callback when a function
- `callback` (function) - Optional - Completion callback
### Returns
Nothing.
```
--------------------------------
### express(options)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/index.md
Creates a new Application instance with the given settings. This is the default export of the module.
```APIDOC
## `express(options)` — default export
### Description
Creates a new `Application` instance with the given settings. This is the default export of the module.
### Method
`express(options)` — function call
### Endpoint
`express(options)`
### Parameters
- `options` (Settings) - Optional - Constructor settings; see configuration.md. Defaults to `{}` (a null-prototype object).
### Returns
An `Application` instance (typed as `UltimateExpress`).
### Throws
`Error('uwsOptions.key_file_name and uwsOptions.cert_file_name are required for HTTP/3')` when `options.http3` is `true` but the uWS TLS files are missing.
### Example
```js
const express = require("ultimate-express");
const app = express();
```
```
--------------------------------
### Application constructor
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Constructor for the Application class. It initializes the uWS app based on settings (plain, SSL, or HTTP/3), sets up caches, engines, locals, and defaults. Throws an Error if HTTP/3 is enabled without key_file_name and cert_file_name in uwsOptions.
```javascript
constructor(settings = new NullObject()) {
super(settings);
if(!settings?.uwsOptions) {
settings.uwsOptions = {};
}
if(typeof settings.threads !== 'number') {
settings.threads = cpuCount > 1 ? 1 : 0;
}
if(settings.uwsApp) {
this.uwsApp = settings.uwsApp;
} else if(settings.http3) {
if(!settings.uwsOptions.key_file_name || !settings.uwsOptions.cert_file_name) {
throw new Error('uwsOptions.key_file_name and uwsOptions.cert_file_name are required for HTTP/3');
}
this.uwsApp = uWS.H3App(settings.uwsOptions);
} else if(settings.uwsOptions.key_file_name && settings.uwsOptions.cert_file_name) {
this.uwsApp = uWS.SSLApp(settings.uwsOptions);
} else {
this.uwsApp = uWS.App(settings.uwsOptions);
}
this.ssl = settings.uwsOptions.key_file_name && settings.uwsOptions.cert_file_name;
this.cache = new NullObject();
this.engines = {};
this.locals = {
settings: this.settings
};
this.listenCalled = false;
this.workers = [];
for(let i = 0; i < settings.threads; i++) { ... } // FSWorker pool, shared between instances
this.port = undefined;
for(const key in defaultSettings) {
if(typeof this.settings[key] === 'undefined') { ... } // fill defaults
}
this.set('view', ViewClass);
this.set('views', path.resolve('views'));
}
```
--------------------------------
### fresh / stale
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/request.md
Returns whether the response is fresh (cacheable and conditionally fresh) or stale. Only valid for GET and HEAD requests.
```APIDOC
## GET /fresh
### Description
Returns true if the request is cacheable and conditionally fresh, false otherwise. Only for GET and HEAD requests. The `stale` getter returns the negation.
### Method
GET
### Endpoint
/fresh
### Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **value** (boolean) - true if fresh, false otherwise.
#### Response Example
true
```
--------------------------------
### render(options, callback) method
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/view.md
Renders the view with the given options and callback. If the engine calls back synchronously, the callback is deferred via `process.nextTick` so user callbacks never run synchronously in the stack. Returns nothing.
```javascript
render(options, callback) {
let sync = true;
this.engine(this.path, options, function onRender() {
if(!sync) {
return callback.apply(this, arguments);
}
return process.nextTick(() => {
return callback.apply(this, arguments);
});
});
sync = false;
}
```
--------------------------------
### enable(key)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Enables a boolean setting by setting it to true. Returns the application instance.
```APIDOC
## enable(key)
### Description
Enables a boolean setting by setting it to true. Returns the application instance.
### Method
enable
### Parameters
- **key** (string) - Required - The setting name.
### Returns
- **this** - The application instance for chaining.
```
--------------------------------
### close(callback)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/application.md
Closes the underlying uWebSockets.js app if it was started with listen(). Invokes the optional callback after closing. Returns nothing.
```APIDOC
## close(callback)
### Description
Closes the underlying uWebSockets.js app if it was started with listen(). Invokes the optional callback after closing. Returns nothing.
### Method
N/A (method call)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```js
const server = app.listen(3000);
setTimeout(() => server.close(() => console.log("closed")), 1000);
```
### Response
#### Success Response
Returns `undefined`.
#### Response Example
```js
app.close(() => console.log("closed"));
```
### Error Handling
No explicit error handling documented.
```
--------------------------------
### Using req.is to check content type
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/request.md
Example usage of `req.is` to check the `Content-Type` header. Returns the matching type or `false`/`null`.
```javascript
app.post("/upload", (req, res) => {
if (req.is("application/json")) { /* ... */ }
res.send("ok");
});
```
--------------------------------
### Using req.get and req.header
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/request.md
Example usage of `req.get` and its alias `req.header` to retrieve request headers. Returns the header value or `undefined` if not present.
```javascript
app.get("/", (req, res) => {
const ct = req.get("Content-Type"); // string | undefined
const ref = req.header("Referer"); // alias
res.send(ct || "none");
});
```
--------------------------------
### use(path, ...callbacks)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Registers middleware or mounts a Router at a specified path. Supports path-prefix matching and emits 'mount' events for mounted routers.
```APIDOC
## USE [path]
### Description
Registers middleware or mounts a Router at the given path. If the first argument is a function or Router, the path defaults to '' (all paths). Mounted routers have their mountpath and parent set, and a 'mount' event is emitted.
### Method
USE
### Endpoint
[path]
### Parameters
#### Path Parameters
- **path** (string | RegExp | function | Router | array of those) - Optional - Default: '' (all paths) when the first argument is a callback/router.
#### Query Parameters
- **callbacks** (Handler[] | Router[]) - Required - Middleware chain or mountables; arrays are flattened.
### Request Example
```js
app.use('/api', apiRouter);
app.use((req, res, next) => next());
```
### Response
#### Success Response (200)
- **this** (Router) - The router instance for chaining.
#### Response Example
```js
// Returns the router instance
```
```
--------------------------------
### Router constructor with settings normalization
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Initializes the Router instance, setting up internal maps, mountpath, request/response prototypes, and normalizing caseSensitive and strict settings into Express-style keys. Defaults 'case sensitive routing' to true if not set.
```javascript
constructor(settings = {}) {
super();
this._paramCallbacks = new Map();
this._mountpathCache = new Map();
this._routes = [];
this.mountpath = '/';
this.settings = settings;
this._request = Request;
this._response = Response;
this.request = this._request.prototype;
this.response = this._response.prototype;
if(typeof settings.caseSensitive !== 'undefined') {
this.settings['case sensitive routing'] = settings.caseSensitive;
delete this.settings.caseSensitive;
}
if(typeof settings.strict !== 'undefined') {
this.settings['strict routing'] = settings.strict;
delete this.settings.strict;
}
if(typeof this.settings['case sensitive routing'] === 'undefined') {
this.settings['case sensitive routing'] = true;
}
for(let method of methods) {
this[method] = (path, ...callbacks) => {
return this.createRoute(method, path, this, ...callbacks);
};
};
}
```
--------------------------------
### Create express app with threads and SSL options
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/configuration.md
Shows how to instantiate an express app with a worker thread pool for file reads and SSL key/cert files. The `http3` option is set to false, and `uwsOptions` includes `key_file_name` and `cert_file_name` to enable SSL mode.
```javascript
const express = require("ultimate-express");
const app = express({
threads: 2, // file-read worker pool
http3: false,
uwsOptions: {
key_file_name: "server.key", // enables SSL mode
cert_file_name: "server.crt",
},
});
```
--------------------------------
### get(field)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/request.md
Retrieves the value of a request header by name (case-insensitive). The 'referrer' and 'referer' headers are unified. An alias 'header' is also available.
```APIDOC
## GET /request/get
### Description
Retrieves the value of a request header by name (case-insensitive). The 'referrer' and 'referer' headers are unified. An alias 'header' is also available.
### Method
GET
### Endpoint
/request/get
### Parameters
#### Path Parameters
- `field` (string) - Required - Header name (case-insensitive)
### Request Example
```js
app.get("/", (req, res) => {
const ct = req.get("Content-Type"); // string | undefined
const ref = req.header("Referer"); // alias
res.send(ct || "none");
});
```
### Response
#### Success Response (200)
- Returns `string | string[] | undefined` - the header value (array for distinct `set-cookie`). `referrer`/`referer` are unified.
#### Response Example
```js
// Example response
"application/json"
```
### Error Handling
- Throws `TypeError('name argument is required to req.get')` when `field` is falsy.
- Throws `TypeError('name must be a string to req.get')` for non-strings.
```
--------------------------------
### render(view, options, callback)
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/response.md
Renders a view with the given options and callback. Sets `options._locals = this.locals` and delegates to `this.req.app.render(...)`, so mounted sub-apps resolve views with their own settings/engines. Default callback is `(err, str) => { err ? req.next(err) : res.send(str) }`.
```javascript
// src/response.js:666-683
render(view, options, callback) { ... }
```
--------------------------------
### Router constructor
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/router.md
Documentation for the Router class constructor, including parameters and behavior.
```APIDOC
## Router Constructor
### Description
Creates a new Router instance with optional settings for case-sensitive and strict routing. The constructor installs route-registration methods for each HTTP method.
### Method
constructor
### Endpoint
new Router(settings)
### Parameters
#### Constructor Parameters
- **settings** (object) - Optional - Configuration object. Recognized keys: `caseSensitive` (boolean), `strict` (boolean), `mergeParams` (boolean). Extra keys are stored in `settings`.
### Returns
- **Router** - A new Router instance.
### Example
```js
const router = new Router({ caseSensitive: true, strict: false });
```
```
--------------------------------
### fresh and stale getters
Source: https://github.com/dimdengd/ultimate-express/blob/main/_autodocs/api-reference/request.md
Getter that returns true if the response is cacheable and conditionally fresh, false otherwise. Only HEAD and GET requests are considered. The stale getter is the negation of fresh.
```javascript
// src/request.js:319-355
get fresh() {
if(this.method !== 'HEAD' && this.method !== 'GET') {
return false;
}
if((this.res.statusCode >= 200 && this.res.statusCode < 300) || this.res.statusCode === 304) {
// fast path: scans raw headers for if-none-match / if-modified-since,
// then delegates to the `fresh` package with the response etag/last-modified
...
return fresh(this.headers, {
'etag': this.res.headers['etag'],
'last-modified': this.res.headers['last-modified'],
});
}
return false;
}
get stale() { return !this.fresh; }
```