How to extend REST API functionality with middleware

Route middleware

Middleware with the REST API are just the usual Express middleware. You may define a list of middleware to run before a route using the .middleware() method on a route instance:

const { route } = require('@tensei/core')

route('Download invoices')
    .middleware([async (request, response, next) => {
        if (! request.user.invoices) {
            return response.status(401).json({
                message: 'You are not authorized to download invoices.'

    .handle((request, response) => request.users.invoices)

You may also define middleware on existing routes. To get an existing route, for example those generated by tensei, you may use the getRoute() method. A good place to do this would be in the .register() hook:

const { tensei } = require('@tensei/core')

    .register(({ getRoute }) => {

Global middleware

Since middleware use the underlying express server, you may define middleware directly on the express instance. A good place to do this would be the .register() hook:

const { tensei } = require('@tensei/core')
const pino = require('express-pino-logger')()

    .register(({ app }) => {