The serverMiddleware Property (En)

  • Type: Array
    • Items: String or Object or Function

⚠Cette page est actuellement en cours de traduction française. Vous pouvez repasser plus tard ou participer à la traduction de celle-ci dès maintenant !

Nuxt internally creates a [connect]( instance, so we can register our middleware to its stack and having chance to provide more routes like API **without need to an external server**. Because connect itself is a middleware, registered middleware will work with both `nuxt start` and also when used as a middleware with programmatic usages like [express-template]( Nuxt [Modules](/guide/modules) can also provide `serverMiddleware` using [this.addServerMiddleware()](/api/internals-module-container#addservermiddleware-middleware-)

serverMiddleware vs middleware!

Don't confuse it with routes middleware which are being called before each route by Vue in Client Side or SSR. serverMiddleware are just running in server side before vue-server-renderer and can be used for server specific tasks like handling API requests or serving assets.


If middleware is String Nuxt.js will try to automatically resolve and require it.

Example (nuxt.config.js):

const serveStatic = require('serve-static')

module.exports = {
  serverMiddleware: [
      // Will register redirect-ssl npm package

      // Will register file from project api directory to handle /api/* requires
      { path: '/api', handler: '~/api/index.js' },

      // We can create custom instances too
      { path: '/static2', handler: serveStatic(__dirname + '/static2') }

HEADS UP! If you don't want middleware to register for all routes you have to use Object form with specific path, otherwise nuxt default handler won't work!

Custom Server Middleware

It is also possible writing custom middleware. For more information See Connect Docs.

Middleware (api/logger.js):

module.exports = function (req, res, next) {
    // req is the Node.js http request object

    // res is the Node.js http response object

    // next is a function to call to invoke the next middleware
    // Don't forget to call next at the end if your middleware is not an endpoint!

Nuxt Config (nuxt.config.js):

serverMiddleware: [

Vous avez vu une erreur ou vous souhaitez contribuer à la documentation ? Éditez cette page sur GitHub !