Bit Hacker Logo
Bit Hacker Logo
Use Express with Nuxt.js

Use Express with Nuxt.js

If you are using Nuxt.js chances are you have had some experience with express one way or another. Maybe your planning a Nuxt.js project and are wondering how extensible it is. While the Nuxt.js project uses connect for routing it is possible to use express for something like an API and get all the benefits of exisiting parsers and plugins.

Setup serverMiddleware

Open up your nuxt.config.js and add the following to your serverMiddleware array. You may have to create a new property in the config:

    serverMiddleware: [
        '~/api/index.js',
    ]

Now create a folder called api and a file called index.js and set it up with the following:

const express = require('express')
const app = express()

app.get('/echo/:what', (req, res) => {
    res.json(req.params)
})

module.exports = {
   path: '/api',
   handler: app
}

Now fire up your Nuxt.js project and visit /api/echo/hello-world and you should see the following output:

{
    "what": "hello-world"
}

Now you have the full power of express along with its plugins to power your Nuxt.js project!