The serverMiddleware property

Define server-side middleware.


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

Nuxt internally creates a connect instance that you can add your own custom middleware to. This allows us to register additional routes (typically /api routes) without need for 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 can also provide serverMiddleware using this.addServerMiddleware()

Additional to them, we introduced a prefix option which defaults to true. It will add the router base to your server middlewares.

Example:

  • Server middleware path: /server-middleware
  • Router base: /admin
  • With prefix: true (default): /admin/server-middleware
  • With prefix: false: /server-middleware

serverMiddleware vs middleware!

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

The serverMiddleware Property - 图1

Do not add serverMiddleware to the middleware/ directory.Middleware, are bundled by webpack into your production bundle and run on beforeRouteEnter. If you add serverMiddleware to the middleware/ directory it will be wrongly picked up by Nuxt as middleware and will add wrong dependencies to your bundle or generate errors.

Usage

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

nuxt.config.js

  1. import serveStatic from 'serve-static'
  2. export default {
  3. serverMiddleware: [
  4. // Will register redirect-ssl npm package
  5. 'redirect-ssl',
  6. // Will register file from project server-middleware directory to handle /server-middleware/* requires
  7. { path: '/server-middleware', handler: '~/server-middleware/index.js' },
  8. // We can create custom instances too
  9. { path: '/static2', handler: serveStatic(__dirname + '/static2') }
  10. ]
  11. }

The serverMiddleware Property - 图2

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 to write custom middleware. For more information See Connect Docs.

Middleware (server-middleware/logger.js):

server-middleware/logger.js

  1. export default function (req, res, next) {
  2. // req is the Node.js http request object
  3. console.log(req.url)
  4. // res is the Node.js http response object
  5. // next is a function to call to invoke the next middleware
  6. // Don't forget to call next at the end if your middleware is not an endpoint!
  7. next()
  8. }

nuxt.config.js

  1. serverMiddleware: ['~/server-middleware/logger']

Custom API endpoint

A server middleware can also extend Express. This allows the creation of REST endpoints.

server-middleware/rest.js

  1. const bodyParser = require('body-parser')
  2. const app = require('express')()
  3. app.use(bodyParser.json())
  4. app.all('/getJSON', (req, res) => {
  5. res.json({ data: 'data' })
  6. })
  7. module.exports = app

nuxt.config.js

  1. serverMiddleware: [
  2. { path: "/server-middleware", handler: "~/server-middleware/rest.js" },
  3. ],

Object Syntax

If your server middleware consists of a list of functions mapped to paths:

  1. export default {
  2. serverMiddleware: [
  3. { path: '/a', handler: '~/server-middleware/a.js' },
  4. { path: '/b', handler: '~/server-middleware/b.js' },
  5. { path: '/c', handler: '~/server-middleware/c.js' }
  6. ]
  7. }

You can alternatively pass an object to define them, as follows:

  1. export default {
  2. serverMiddleware: {
  3. '/a': '~/server-middleware/a.js',
  4. '/b': '~/server-middleware/b.js',
  5. '/c': '~/server-middleware/c.js'
  6. }
  7. }