Middleware
MIDDLEWARE(), USE(), MiddlewareOptions and the $ object of a middleware.
On this page
API
method
MIDDLEWARE(name, fn, [types], [first])
Registers, replaces or removes a named middleware.
MIDDLEWARE(name, fn, [types], [first])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name used in route flags (#name) and in USE(). |
fn |
Function($) |
The middleware, or null to remove it. |
types |
String|String[] |
Assigns the middleware globally to these request types. |
first |
Boolean |
With types, puts the middleware before the others. |
fn receives one argument, $ (MiddlewareOptions). It must call $.next(), call $.cancel(), or respond with $.res; otherwise the request waits until its timeout. A middleware that is not registered but assigned to a route is skipped and logged as Middleware not found.
With types, the middleware is also assigned globally by calling USE(name, '', types, first). Use a type name or an array: web, file, websocket, all.
fn = null removes the middleware and removes its name from all routes and global lists. NEWMIDDLEWARE() is the same function. Middleware registered by a plugin or another owner is removed when that owner is unloaded.
MIDDLEWARE('apikey', function($) {
if ($.headers['x-api-key'] === CONF.apikey)
$.next();
else
$.res.throw401();
});
exports.install = function() {
ROUTE('GET /api/products/', products, ['#apikey']);
};
MIDDLEWARE('cors', function($) {
$.res.setHeader('Access-Control-Allow-Origin', '*');
$.next();
}, ['file']);
MIDDLEWARE('apikey', null);
method
USE(name, [url], [types], [first])
Assigns middleware to all requests, to one type of request, or to routes under a URL.
USE(name, [url], [types], [first])| Parameter | Type | Description |
|---|---|---|
name |
String|String[]|Function |
Middleware name(s), or a function. |
url |
String|String[] |
A URL prefix. An array here is taken as types. |
types |
String|String[] |
Request types: web, file, websocket, all. |
first |
Boolean |
Puts the middleware before the middleware already assigned. |
USE() runs after the application is loaded, so it sees the routes from all controllers.
- Without
urlandtypes, or with the typeallor*, the middleware runs for every request, static files included, before the routing.$.controlleris not set there. - With
typesonly, it runs for every request of those types.web(alsoroute,routes,dynamic,http,https,api,schema,schemas) means dynamic routes;file(alsofiles,static) means static files and file routes;websocket(alsosocket,sockets,websockets,ws,wss) means WebSocket routes. - With
urlandtypes, it is added to each existing route of those types whose URL starts withurl. Aurlof*means no URL.
name can be a string with several names separated by commas or spaces (a leading # or & is ignored), an array of names, or a function, which is registered as a middleware with a generated name. A name that is already in a list is not added twice.
USE('poweredby');
USE('apikey', '/api/', ['web']);
USE(function($) {
console.log('WebSocket', $.url);
$.next();
}, ['websocket']);
class
$
The argument of every middleware function.
$A new instance is created for each chain of middleware of a request. Besides the methods below, it has these read-only shortcuts:
| Property | Value |
|---|---|
$.req, $.res | The request and the response (for WebSocket routes, $.res is the WebSocket client) |
$.user, $.session, $.sessionid | The user and session set by authorization |
$.headers, $.ip, $.ua, $.language | Request data |
$.url, $.path, $.split | The URL and its parts |
$.query, $.body, $.files | Query string, parsed body and uploaded files |
$.params, $.id | Route parameters and the controller ID (only when $.controller exists) |
$.controller | The controller, in middleware of dynamic routes |
$.options | The options object of the route |
$.middleware | The list of names in the current chain |
MIDDLEWARE('logger', function($) {
console.log($.ip, $.url, $.ua);
$.next();
});
method
$.next([err])
Continues with the next middleware, or with the action when this was the last one.
$.next([err])| Parameter | Type | Description |
|---|---|---|
err |
Boolean|Error|ErrorBuilder |
false to stop, or an error to respond with 500. |
- No argument: continue.
false: stop the chain; the action is not run.- An
Erroror anErrorBuilder: respond with an error 500 and stop.
If the response was already sent, the chain stops by itself.
MIDDLEWARE('maintenance', function($) {
if (CONF.maintenance)
$.next(new Error('Maintenance'));
else
$.next();
});
method
$.cancel()
Stops the chain of middleware without running the action.
$.cancel()Returns MiddlewareOptions
The same as $.next(false). Use it after you have sent a response yourself. Returns $.
MIDDLEWARE('ping', function($) {
if ($.url === '/ping/') {
$.res.send(200, 'pong', 'text/plain');
$.cancel();
} else
$.next();
});
method
$.callback()
Continues the chain; the same as $.next() without an argument.
$.callback()Returns MiddlewareOptions
Returns $.
MIDDLEWARE('log', function($) {
console.log($.url);
$.callback();
});
property
$.options
The options object from the flags of the route.
$.optionsReturns Object
An object in the flags array of ROUTE() or a file route becomes $.options in all middleware of that route. For global middleware it is an empty object.
MIDDLEWARE('role', function($) {
if ($.user && $.user.roles.includes($.options.role))
$.next();
else
$.res.throw403();
});
exports.install = function() {
ROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);
ROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);
};
property
$.controller
The controller of the request, in middleware of dynamic routes.
$.controllerReturns Controller
It is set for middleware of a route and for middleware assigned with USE(name, ...['web']). In global middleware of all requests, static files and file routes it is undefined. $.params and $.id read from it.
MIDDLEWARE('product', function($) {
if ($.params.id)
$.next();
else
$.controller.throw404();
});
method
PATH.middleware([filename])
Returns the absolute path to a file in the middleware directory.
PATH.middleware([filename])| Parameter | Type | Description |
|---|---|---|
filename |
String |
A file name. |
Returns String An absolute path.
The directory is set by directory_middleware.
PATH.middleware('auth.js');
config
directory_middleware
The directory with middleware files. Default /middleware/.
directory_middlewareReturns String '/middleware/'
Each .js file is loaded at startup and its exports.install() is called. Register the middleware there with MIDDLEWARE().
// /middleware/auth.js
exports.install = function() {
MIDDLEWARE('auth', function($) {
if ($.user)
$.next();
else
$.res.throw401();
});
};