Static GitHub Issues

[1312] Use express instead of connect to enable full power of express in Nuxt apps

prev: Failed to resolve directive: dragula
next: specify the transition of <nuxt /> subcomponent in layout component

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)
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1161">#c1161</a>)</em></sub></div>