Nuxt.js: Use express instead of connect to enable full power of express in Nuxt apps

Created on 7 Aug 2017  路  7Comments  路  Source: nuxt/nuxt.js

I would like to be able to create REST APIs in a Nuxt app that I am making. I could use the express example, where Nuxt itself is just an express middleware, but that just makes using Nuxt a bit more complex to use.

Possibilities straight out of the box

1. serverMiddleware

I can currently create REST APIs, to a degree, by using the serverMiddleware key in nuxt.config.js:

serverMiddleware: [
    {
        path: '/helloapi',
        handler(req, res, next) {
            res.setHeader("Content-Type", "application/json")
            res.end(JSON.stringify({ this: 'is', a: 'test'}))
        }
    }
]

2. Nuxt middleware

I can also create a Nuxt middleware

/middleware/api.js

export default function (context) {
    let req = context.req
    if (req) {
        let res = context.res
        if (req.url === '/myapi') {
            res.setHeader("Content-Type", "application/json")
            res.end(JSON.stringify({ message: 'Hello World' }))
        }
    }
}

and configure it in nuxt.config.js:

router: {
    middleware: 'api'
}

Both of the above solutions allow me to create a REST API. However, they lack the power of express. So, I have to handle parsing routes, url parameters and REST arguments, like '/myapi/42', myself. This is not optimal, but doable.

Propose to use express instead of connect

In renderer.js around line 17 there is a line that imports connect

import connect from 'connect'

If we change it to

import connect from 'express'

In conclusion...

By using express, we could use it's full power to parse routes with parameters, such as "/user/paul/post/7", without writing our own parsing code. We would also get many other helpers, such as res.json(), etc...

I made that change on a fork and did some limited testing on my app and it seems to work just fine. I'm not sure what other implications there are, so, just want run it by you.

Here are a couple of question I have:

  1. Are you guys open to implementing this?
  2. Will it break anything (assuming you've already tried this before)

This question is available on Nuxt.js community (#c1161)

Most helpful comment

Hi. Thanks for your idea. Actually, it is possible using express with serverMiddleware, I think there would be no reason using express instead of connect as main glue. The reason is that not any nuxt internal needs features from express like router or query parser so it may just introduce overhead and more dependencies. Also as express modifies req and res objects, it may introduce unwanted side-effects when used in conjunction with other frameworks (express in express or express in hapi!)

BTW Don't be sad as internal express support is already possible with the magic of how middleware and connect works. Simply you can create an express instance and register it as a nuxt middleware:

serverMiddleware/api.js

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

app.get('/', (req, res) => {
  res.json({ it: 'works!' })
})

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

Demo: https://nuxt-with-express.glitch.me/
https://glitch.com/edit/#!/nuxt-with-express

All 7 comments

Hi. Thanks for your idea. Actually, it is possible using express with serverMiddleware, I think there would be no reason using express instead of connect as main glue. The reason is that not any nuxt internal needs features from express like router or query parser so it may just introduce overhead and more dependencies. Also as express modifies req and res objects, it may introduce unwanted side-effects when used in conjunction with other frameworks (express in express or express in hapi!)

BTW Don't be sad as internal express support is already possible with the magic of how middleware and connect works. Simply you can create an express instance and register it as a nuxt middleware:

serverMiddleware/api.js

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

app.get('/', (req, res) => {
  res.json({ it: 'works!' })
})

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

Demo: https://nuxt-with-express.glitch.me/
https://glitch.com/edit/#!/nuxt-with-express

@pi0 That's great :) It works as I need it to. Thanks a lot.

I think we should add your explanation, above, to the Guide, as it makes the whole process easy!

I had no idea that express could itself be used as a middleware. I was actually looking for this, but found nothing until your reply.

@pbastowski Your welcome and thanks for opening this topic. I try to add some guide for serverMiddleware section in 1.x docs.

Sorry to revive a closed issue, but I've done everything as @pi0 said and it works fine. The problem is when I change anything in my api.js file it's not reflected in the browser until I restart nuxt.
Any idea why? Did I do something wrong, or there something extra that I need to do here? It doesn't make sense to kill nuxt every time I make a change in api.js

This is normal behavior, which is why you may want to run express separately and proxy to it from nuxt.

When express runs separately you will have to restart it when changes to files are made, which is also normal behavior. You can use nodemon to restart it.

This setup will prevent nuxt from having to be restarted.

Got it, thanks for clarifying that.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

uptownhr picture uptownhr  路  3Comments

VincentLoy picture VincentLoy  路  3Comments

pehbehbeh picture pehbehbeh  路  3Comments

vadimsg picture vadimsg  路  3Comments

shyamchandranmec picture shyamchandranmec  路  3Comments