---
title: Middleware
project: Total.js V4
version: 0.0.99
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/guides/middleware/
updated: 2026-11-16T15:50:00.282Z
---

# Middleware

> Run code before routes and files with MIDDLEWARE(), in a route or for many routes at once with USE().

## Defining a middleware

`MIDDLEWARE(name, fn)` registers a function under a name. The function receives one argument, `$`, an instance of [MiddlewareOptions](../../reference/middleware/). Call `$.next()` to continue, or answer the request with `$.res` and do not call it:

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

A middleware must always call `$.next()`, `$.cancel()`, or respond. If it does none of them, the request waits until it times out. `$.next(err)` with an `Error` or an `ErrorBuilder` responds with an error 500. `$.next(false)` and `$.cancel()` stop the chain without running the action.

`NEWMIDDLEWARE()` is the same function under its newer name. Passing `null` as the function removes the middleware and unassigns it from all routes:

```js
MIDDLEWARE('apikey', null);
```

Put middleware into the `/middleware/` directory (the config key `directory_middleware`). Each file is loaded like a controller, so register the middleware in `exports.install`:

```js
// /middleware/apikey.js
exports.install = function() {
	MIDDLEWARE('apikey', function($) {
		$.next();
	});
};
```

## Using a middleware in a route

Add the name with `#` (or `&`) to the flags of a route. The middleware runs after the route has been matched and before the action, in the order of the flags:

```js
exports.install = function() {
	ROUTE('GET /api/products/', products, ['#apikey']);
	ROUTE('POST /api/orders/', orders, ['#apikey', '#logger']);
};
```

HTTP routes also accept the inline form in the URL:

```js
ROUTE('GET /api/products/ &apikey', products);
```

An object in the flags becomes `$.options` in the middleware. In this way, one middleware can be configured for each route:

```js
MIDDLEWARE('role', function($) {
	if ($.user && $.user.roles.includes($.options.role))
		$.next();
	else
		$.res.throw403();
});

exports.install = function() {
	ROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);
};
```

For routes, `$.controller` is the controller of the request and `$.params` holds the route parameters. See [Routing](../routing/) for the other flags.

## Global middleware

`USE(name, [url], [types], [first])` assigns a middleware to many routes at once. Without `url` and `types`, it runs for **every** request, static files included, before the routing:

```js
MIDDLEWARE('poweredby', function($) {
	$.res.setHeader('X-Server', 'MyApp');
	$.next();
});

USE('poweredby');
```

With `types`, the middleware runs only for one kind of request. `web` means dynamic routes, `file` means static files and file routes, and `websocket` means WebSocket routes (`all` or `*` means every request):

```js
// Only dynamic routes
USE('apikey', ['web']);

// Only routes whose URL starts with /api/
USE('apikey', '/api/', ['web']);
```

With a `url`, the middleware is added to the routes that already exist and whose URL starts with it. `USE()` waits until the application is loaded, so it sees all the routes from controllers. `first: true` puts the middleware before the others. The third argument of `MIDDLEWARE(name, fn, types, first)` calls `USE(name, '', types, first)` for you:

```js
MIDDLEWARE('cors', function($) {
	$.res.setHeader('Access-Control-Allow-Origin', '*');
	$.next();
}, ['file']);
```

The order is: middleware of all requests, then middleware of static files (for files), or for routes the middleware of the route, then the middleware of all dynamic routes, then the action.
