# Add a middleware to a route

> Register a middleware with MIDDLEWARE() and attach it to routes with the #name flag.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 21a8ac10bfbd464e0e9bceb13feb511303bd458fb154b488fc83b90d57a5a10c
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

A middleware is a function that runs before the route handler. Call `next()` to continue or answer the request yourself to stop it. Register it once with `MIDDLEWARE(name, fn)` and attach it to a route with `#name`.

```js definitions/middleware.js
MIDDLEWARE('apikey', function($, next) {
	if ($.headers['x-api-key'] === 'abc123')
		next();
	else
		$.invalid(401);
});
```

```js controllers/secure.js
exports.install = function() {
	ROUTE('GET /secure/ #apikey', secure);
	ROUTE('GET /open/', open);
};

function secure($) {
	$.json({ ok: true });
}

function open($) {
	$.json({ ok: true });
}
```
