Routes are loaded as a module, with each HTTP method as an export, affording a very customizable API server.
You can use res to:
res.send(body[, status, headers])
res.redirect(url)
res.error(status[, Error])
Route Types
Protected Routes
Protected routes require authorization for access and will redirect to authentication endpoints if needed.
Unprotected Routes
Unprotected routes do not require authorization for access and will exit the authorization pipeline early to avoid rate limiting, CSRF tokens, & other security measures. These routes are the DMZ of your API! Youmust secure these endpoints with alternative methods if accepting input!
Exit Routes
As of 17.2.0 you can have routes exit the middleware pipeline immediately by setting them in the exit Array. This differs from unprotect as there is no request body handling.
Reserved Route
The /assets/* route is reserved for the HTML browsable interface assets; please do not try to reuse this for data.
Advanced Routing Examples
// Middleware for all requestsexport const always = { "/": (req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }};// Protected routes with authenticationexport const get = { "/admin": (req, res) => { // Only accessible after authentication res.json({admin: true}); }};// Route parametersexport const get = { "/users/:id": (req, res) => { const userId = req.params.id; res.json({id: userId}); }};
🔧 Request and Response Helpers
Request Helpers
Tenso decorates req with helpers such as:
req.allow - Allowed HTTP methods
req.csrf - CSRF token information
req.ip - Client IP address
req.parsed - Parsed URL information
req.private - Private route flag
req.body - Request payload for PATCH, PUT, & POST requests
req.session - Session data when using local authentication
Response Helpers
Tenso decorates res with helpers such as:
res.send() - Send response with optional status and headers
res.status() - Set response status
res.json() - Send JSON response
res.redirect() - Send redirect response
res.error() - Send error response
🎛️ Extensibility
Tenso is extensible and can be customized with custom parsers, renderers, & serializers.
Parsers
Custom parsers can be registered with server.parser('mimetype', fn); or directly on server.parsers. The parameters for a parser are (arg).
Tenso has built-in parsers for:
application/json
application/x-www-form-urlencoded
application/jsonl
application/json-lines
text/json-lines
Renderers
Custom renderers can be registered with server.renderer('mimetype', fn);. The parameters for a renderer are (req, res, arg).
Tenso has built-in renderers for:
application/javascript
application/json
application/jsonl
application/json-lines
text/json-lines
application/yaml
application/xml
text/csv
text/html
Serializers
Custom serializers can be registered with server.serializer('mimetype', fn);. The parameters for a serializer are (arg, err, status = 200, stack = false).
Tenso has two default serializers which can be overridden:
Responses will have a standard shape and will be UTF-8 by default. The result will be in data. Hypermedia (pagination & links) will be in links: [{"uri": "...", "rel": "..."}, ...], & also in the Link HTTP header.
Page size can be specified via the page_size parameter, e.g. ?page_size=25.
Sort order can be specified via the order-by parameter which accepts [field ]asc|desc & can be combined like an SQL 'ORDER BY', e.g. ?order_by=desc or ?order_by=lastName%20asc&order_by=firstName%20asc&order_by=age%20desc
🌐 REST / Hypermedia
Hypermedia is a prerequisite of REST and is best described by the Richardson Maturity Model. Tenso will automatically paginate Arrays of results, or parse Entity representations for keys that imply relationships, and create the appropriate Objects in the link Array, as well as the Link HTTP header. Object keys that match this pattern: /_(guid|uuid|id|uri|url)$/ will be considered hypermedia links.
For example, if the key user_id was found, it would be mapped to /users/:id with a link rel of related.
Tenso will bend the rules of REST when using authentication strategies provided by passport.js, or CSRF if enabled, because they rely on a session. Session storage is in memory or Redis. You have the option of a stateless or stateful API.
Hypermedia processing of the response body can be disabled as of 10.2.0 by setting req.hypermedia = false and/or req.hypermediaHeader via middleware.
⚙️ Configuration
Tenso provides comprehensive configuration options to customize every aspect of your server. All configuration options are optional - provide only what you need to override the sensible defaults.
## 🔐 AuthenticationThe `protect` Array contains the endpoints that will require authentication. The `redirect` String is the endpoint users will be redirected to upon successfully authenticating; the default is `/`.Sessions are used for non-`Basic` or `Bearer Token` authentication and will have `/login`, `/logout`, & custom routes. Redis is supported for session storage.Multiple authentication strategies can be enabled at once.Authentication attempts have a random delay to deal with "timing attacks"; always rate limit in production environments!### Basic Auth```javascript{ "auth": { "basic": { "enabled": true, "list": ["username:password"] }, "protect": ["/"] }}
JSON Web Token
JSON Web Token (JWT) authentication is stateless and does not have an entry point. The auth(token, callback) function must verify token.sub and must execute callback(err, user).
This authentication strategy relies on out-of-band information for the secret and other optional token attributes.
{ "auth": { "jwt": { "enabled": true, "auth": function (token, cb) { /* Authentication handler to 'find' or 'create' a User */ }, "algorithms": ["HS256", "HS384", "HS512"], // Optional signing algorithms "audience": "", // Optional, used to verify 'aud' "issuer": "", // Optional, used to verify 'iss' "ignoreExpiration": false, // Optional, set to true to ignore expired tokens "scheme": "Bearer", // Optional, set to specify the Authorization scheme "secretOrKey": "" }, "protect": ["/private"] }}
OAuth2
OAuth2 authentication will create /auth, /auth/oauth2, & /auth/oauth2/callback routes. auth(accessToken, refreshToken, profile, callback) must execute callback(err, user).
{ "auth": { "oauth2": { "enabled": true, "auth": function (accessToken, refreshToken, profile, callback) { /* Authentication handler */ }, "auth_url": "", // Authorization URL "token_url": "", // Token URL "client_id": "", // Get this from authorization server "client_secret": "" // Get this from authorization server }, "protect": ["/private"] }}
SAML authentication will create /auth, /auth/saml, & /auth/saml/callback routes. auth(profile, callback) must execute callback(err, user).
Tenso uses passport-saml; for configuration options please visit its homepage.
{ "auth": { "saml": { "enabled": true // Additional SAML configuration options go here }, "protect": ["/private"] }}
💾 Sessions
Sessions can use a memory (default) or Redis store. Memory will limit your sessions to a single server instance, while Redis will allow you to share sessions across a cluster of processes or machines. To use Redis, set the store property to "redis".
If the session secret is not provided, a version 4 UUID will be used.
Tenso uses helmet for security headers as middleware. Please see its documentation for how to configure it; each method & argument is a key:value pair for security.
Rate limiting is controlled by configuration and is disabled by default. Rate limiting is based on token, session, or ip, depending upon authentication method.
Rate limiting can be overridden by providing an override function that takes req & rate and must return a (modified) rate.
{ "rate": { "enabled": true, "limit": 450, // Maximum requests allowed before reset "reset": 900, // TTL in seconds "status": 429, // Optional HTTP status "message": "Too many requests", // Optional error message "override": function (req, rate) { /* Override the default rate limiting */ } }}
📁 Upload Size Limiting
A 'max byte' limit can be enforced on all routes that handle PATCH, POST, & PUT requests. The default limit is 0 (unlimited).
{ "maxBytes": 5242880 // 5MB limit}
📊 Logging
Standard log levels are supported and are emitted to stdout & stderr. Stack traces can be enabled.
Tenso includes a comprehensive benchmark suite for performance analysis and optimization. The benchmark suite tests all major framework components including HTTP handling, authentication, parsing, rendering, serialization, hypermedia generation, rate limiting, memory usage, and real-world load testing.
# Run all benchmarksnpm run benchmark# Run comprehensive load testnpm run benchmark:load-test# Run individual benchmark suitesnpm run benchmark:basic # Basic HTTP performancenpm run benchmark:auth # Authentication performancenpm run benchmark:parsers # Request parsing performancenpm run benchmark:renderers # Response rendering performancenpm run benchmark:serializers # Data serialization performance npm run benchmark:rate # Rate limiting performancenpm run benchmark:hypermedia # Hypermedia link generationnpm run benchmark:memory # Memory usage analysis