# Middlewares configuration

🤓 Different types of middlewares

In Strapi, 2 middleware concepts coexist:

  • Strapi middlewares are configured and enabled as global middlewares for the entire Strapi server application. The present documentation describes how to configure Strapi middlewares.
    Strapi also offers the ability to implement your own custom middlewares (see middlewares customization documentation).

  • Route middlewares have a more limited scope and are configured and used as middlewares at the route level. They are described in the route middlewares documentation.

The ./config/middlewares.js file is used to define all the Strapi middlewares that should be applied by the Strapi server.

Only the middlewares present in ./config/middlewares.js are applied. Loading middlewares happens in a specific loading order, with some naming conventions and an optional configuration for each middleware.

Strapi prepopulates the ./config/middlewares.js file with built-in, internal middlewares that all have their own configuration options.

# Loading order

The ./config/middlewares.js file exports an array, where order matters and controls the execution order of the middleware stack:

// path: ./config/middlewares.js

module.exports = [
  // The array is pre-populated with internal, built-in middlewares, prefixed by `strapi::`
  'strapi::cors',
  'strapi::body',
  'strapi::errors',
  // ...
  'my-custom-node-module', // custom middleware that does not require any configuration
  {
    // custom resolve to find a package or a path
    resolve: 'my-custom-node-module',
    config: {
      foo: 'bar',
    },
  },
  {
    // custom resolve to find a package or a path
    resolve: '../some-dir/custom-middleware',
    config: {
      foo: 'bar',
    },
  },
];

💡 TIP

If you aren't sure where to place a middleware in the stack, add it to the end of the list.

# Naming conventions

Strapi middlewares can be classified into different types depending on their origin, which defines the following naming conventions:

Middleware type Origin Naming convention
Internal Built-in middlewares (i.e. included with Strapi), automatically loaded strapi::middleware-name
Application-level Loaded from the ./src/middlewares folder global::middleware-name
API-level Loaded from the ./src/api/[api-name]/middlewares folder api::api-name.middleware-name
Plugin Exported from strapi-server.js in the middlewares property of the plugin interface plugin::plugin-name.middleware-name
External Can be:
  • either node modules installed with npm (opens new window)
  • or local middlewares (i.e. custom middlewares created locally and configured in ./config/middlewares.js.)
-

As they are directly configured and resolved from the configuration file, they have no naming convention.

# Optional configuration

Middlewares can have an optional configuration with the following parameters:

Parameter Description Type
config Used to define or override the middleware configuration Object
resolve Path to the middleware's folder (useful for external middlewares) String

# Internal middlewares configuration reference

Strapi's core includes the following internal middlewares, mostly used for performances, security and error handling:

✋ CAUTION

The following built-in middlewares are automatically added by Strapi: errors, security, cors, query', body, public, favicon. They should not be removed as it will throw an error.

# body

The body middleware is based on koa-body (opens new window) and uses these sensible defaults:

Option Description Type Default
multipart Parse multipart bodies Boolean true
patchKoa Patch request body to Koa's ctx.request Boolean true

For a full list of available options, check the koa-body documentation (opens new window).

# compression

The compression middleware is based on koa-compress (opens new window) and offers the same options (opens new window).

# cors

This security middleware is about cross-origin resource sharing (CORS) and is based on @koa/cors (opens new window). It accepts the following options:

Option Type Description Default value
origin Allowed URLs.

The value(s) can be:
  • strings (e.g. http://example1.com, http://example2.com)
  • an array of strings (e.g. ['http://www.example1.com', 'http://example1.com'])
  • or * to allow all URLs
String or Array *
maxAge Configure the Access-Control-Max-Age CORS header parameter, in seconds String or Number 31536000
credentials Configure the Access-Control-Allow-Credentials CORS header Boolean true
methods Configure the Access-Control-Allow-Methods CORS header Array or String ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
headers Configure the Access-Control-Allow-Headers CORS header

If not specified, defaults to reflecting the headers specified in the request's Access-Control-Request-Headers header
Array or String ['Content-Type', 'Authorization', 'Origin', 'Accept']
keepHeaderOnError Add set headers to err.header if an error is thrown Boolean false

# errors

The errors middleware handles errors thrown by the code. Based on the type of error it sets the appropriate HTTP status to the response. By default, any error not supposed to be exposed to the end-user will result in a 500 HTTP response.

The middleware doesn't have any configuration option.

# favicon

The favicon middleware is used to serve the favicon. It's based on koa-favicon (opens new window) and has these sensible defaults:

Option Description Type Default value
path Path to the favicon file String favicon.ico
maxAge Cache-control max-age directive, in milliseconds Integer 86400000

# ip

The ip middleware is an IP filter middleware based on koa-ip (opens new window) and accepts the following options:

Option Description Type Default value
whitelist Whitelisted IPs Array []
blacklist Blacklisted IPs Array []

# logger

The logger middleware is used to log requests.

Option Description Type Default value
enabled Enable requests logs Boolean false

To define a custom configuration for the logger middleware, create a dedicated configuration file (./config/logger.js). It should export an object that must be a complete or partial winstonjs (opens new window) logger configuration. The object will be merged with Strapi's default logger configuration on server start.

Example: Custom configuration for the logger middleware
'use strict';

const {
  winston,
  formats: { prettyPrint, levelFilter },
} = require('@strapi/logger');

module.exports = {
  transports: [
    new winston.transports.Console({
      level: 'http',
      format: winston.format.combine(
        levelFilter('http'),
        prettyPrint({ timestamps: 'YYYY-MM-DD hh:mm:ss.SSS' })
      ),
    }),
  ],
};

# poweredBy

The poweredBy middleware adds a X-Powered-By parameter to the response header, with a default value of Strapi <strapi.io>.

# query

The query middleware is a query parser based on qs (opens new window) and has the following sensible defaults:

Option Description Type Default value
strictNullHandling Distinguish between null values and empty strings (see qs documentation (opens new window)) Boolean true
arrayLimit Maximum index limit when parsing arrays (see qs documentation (opens new window)) Number 100
depth Maximum depth of nested objects when parsing objects (see qs documentation (opens new window)) Number 20

# response-time

The response-time middleware enables the X-Response-Time (in milliseconds) for the response header.

# public

The public middleware is a static file serving middleware, based on koa-static (opens new window). It accepts the following options:

Option Description Type Default value
path Path to the public folder String ./public
maxAge Cache-control max-age directive, in milliseconds Integer 60000
defaultIndex Display default index page at / and /index.html Boolean true

# security

The security middleware is based on koa-helmet (opens new window) and has the following sensible defaults:

Option Description Type Default value
crossOriginEmbedderPolicy Set the Cross-Origin-Embedder-Policy header to require-corp Boolean false
crossOriginOpenerPolicy Set the Cross-Origin-Opener-Policy header Boolean false
crossOriginOpenerPolicy Set the Cross-Origin-Resource-Policy header Boolean false
originAgentCluster Set the Origin-Agent-Cluster header Boolean false
contentSecurityPolicy Set the Content-Security-Policy header Boolean false
xssFilter Disable browsers' cross-site scripting filter by setting the X-XSS-Protection header to 0 false
hsts Set options for the HTTP Strict Transport Security (HSTS) policy.

Accepts the following parameters:
  • maxAge: Number of seconds HSTS is in effect
  • includeSubDomains: Applies HSTS to all subdomains of the host
  • maxAge: Integer
  • includeSubDomains: Boolean
  • maxAge: 31536000
  • includeSubDomains: true
frameguard Set X-Frame-Options header to help mitigate clickjacking attacks

Accepts the action parameter that specifies which directive to use.
String sameorigin