Spanish Total.js
English
Documentation For AI agents
Contents

Middleware

MIDDLEWARE(), USE(), MiddlewareOptions and the $ object of a middleware.

.md GitHub
On this page

API

method

MIDDLEWARE(name, fn, [types], [first])

Registers, replaces or removes a named middleware.
ParameterTypeDescription
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.

Check an API key
MIDDLEWARE('apikey', function($) {
	if ($.headers['x-api-key'] === CONF.apikey)
		$.next();
	else
		$.res.throw401();
});

exports.install = function() {
	ROUTE('GET /api/products/', products, ['#apikey']);
};
Register and assign to all static files
MIDDLEWARE('cors', function($) {
	$.res.setHeader('Access-Control-Allow-Origin', '*');
	$.next();
}, ['file']);
Remove
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.
ParameterTypeDescription
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 url and types, or with the type all or *, the middleware runs for every request, static files included, before the routing. $.controller is not set there.
  • With types only, it runs for every request of those types. web (also route, routes, dynamic, http, https, api, schema, schemas) means dynamic routes; file (also files, static) means static files and file routes; websocket (also socket, sockets, websockets, ws, wss) means WebSocket routes.
  • With url and types, it is added to each existing route of those types whose URL starts with url. A url of * 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.

Every request
USE('poweredby');
Only dynamic routes under /api/
USE('apikey', '/api/', ['web']);
An anonymous middleware for WebSocket routes
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:

PropertyValue
$.req, $.resThe request and the response (for WebSocket routes, $.res is the WebSocket client)
$.user, $.session, $.sessionidThe user and session set by authorization
$.headers, $.ip, $.ua, $.languageRequest data
$.url, $.path, $.splitThe URL and its parts
$.query, $.body, $.filesQuery string, parsed body and uploaded files
$.params, $.idRoute parameters and the controller ID (only when $.controller exists)
$.controllerThe controller, in middleware of dynamic routes
$.optionsThe options object of the route
$.middlewareThe list of names in the current chain
Read request data
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.
ParameterTypeDescription
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 Error or an ErrorBuilder: respond with an error 500 and stop.

If the response was already sent, the chain stops by itself.

Stop with an error
MIDDLEWARE('maintenance', function($) {
	if (CONF.maintenance)
		$.next(new Error('Maintenance'));
	else
		$.next();
});
method

$.cancel()

Stops the chain of middleware without running the action.

Returns MiddlewareOptions

The same as $.next(false). Use it after you have sent a response yourself. Returns $.

Answer and stop
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.

Returns MiddlewareOptions

Returns $.

Continue
MIDDLEWARE('log', function($) {
	console.log($.url);
	$.callback();
});
property

$.options

The options object from the flags of the route.

Returns 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.

One middleware, different settings
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.

Returns 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.

Use the controller
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.
ParameterTypeDescription
filename String A file name.

Returns String An absolute path.

The directory is set by directory_middleware.

Path
PATH.middleware('auth.js');
config

directory_middleware

The directory with middleware files. Default /middleware/.

Returns String '/middleware/'

Each .js file is loaded at startup and its exports.install() is called. Register the middleware there with MIDDLEWARE().

A middleware file
// /middleware/auth.js
exports.install = function() {
	MIDDLEWARE('auth', function($) {
		if ($.user)
			$.next();
		else
			$.res.throw401();
	});
};
Made in Europe