Skip to main content

Adding a middleware

Create a new middleware

To extend functionality and behaviours you can register so called middlewares. There are 5 different kinds (MiddlewareType):

1.before

The Before middleware is called before the request is executed and allows you to manipulate the request. It can be used to add an Authorization Token to the request for example. The request which is handed in should be mutated and returned from the function.

2.success

The Success middleware is called after the request succeeded and allows you to manipulate the response. The middleware gets handed in the request and the direct response from the fetch before it gets manipulated by the after middleware.

3.error

The Error middleware is called after the request fails (throws) and allows you to manipulate the response. It can be used to trigger certain actions on specific error codes for example. The middleware gets handed in the request and the direct response from the fetch before it gets manipulated by the after middleware.

4.unauthorized

The Unauthorized middleware is called when the request fails with a 401 Unauthorized status. It is typically used to refresh the session. Returning true retries the original request, returning false stops the retry (e.g. after a failed refresh), and returning a response replaces the current one.

5.after

The After middleware is called after the request is executed and allows you to manipulate the response. The middleware gets handed in the request and the response which already has been manipulated by the success or error middleware.

Every middleware receives a single context object. before middlewares get { request, app }; all response middlewares (success, error, unauthorized, after) get { request, response, app }.

1. Create a new file middleware.ts in the src/shop/client/api/helpers directory. Now you can create a new middleware as following:

This middleware definition is executed according to the above-mentioned criteria.

import { createMiddleware, HttpHeader } from '@archibald/core';
import { createLogger } from '@archibald/log';

const Logger = createLogger({ prefix: 'middleware' });

export const authBeforeMiddleware = createMiddleware('before', ({ request }) => {
request.headers.set(HttpHeader.AUTHORIZATION, 'Bearer <token>');
return request;
});

export const errorMiddleware = createMiddleware('error', ({ request, response }) => {
Logger.error(`Request to ${request.url} failed with status ${response.status ?? 0}`);
});

2. Register the middleware with the api Instance:

import { authBeforeMiddleware, errorMiddleware } from 'shop/client/api/helpers/middleware';

// API creation
...

api.register([authBeforeMiddleware, errorMiddleware]);

// createRequest export
...