Since Nuxt internally uses Connect as the server, we can add our custom middlewares without the need for an external server such as Koa or Express. You can develop a complex Nuxt server middleware just like we did with Koa and Express in the previous sections. However, let's not endlessly repeat what we have already done. Let's create a very basic custom middleware that prints a "Hello World" message to confirm the feasibility of building a complex one from a basic middleware in the following steps:
- Add the path where we want to create our custom middleware:
// nuxt.config.js
serverMiddleware: [
{ path: '/api', handler: '~/api/index.js' }
]
- Add the API routes to the index.js file inside the /api/ directory:
// api/index.js
export default function (req, res, next) {
res.end('Hello world!')
}
- Run the app with npm run dev and navigate to localhost:3000/api. You should see the ...