Next.js: api routes are not served when using express and body-parser

Created on 10 Aug 2019  路  3Comments  路  Source: vercel/next.js

Bug report

Describe the bug

When using express as custom server and using a body-parser, next stop answering requests in /api routes.

To Reproduce

server.js

const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')

const app = next({dev: true})
const server = express()

app.prepare().then(() => {
  const handle = app.getRequestHandler()
  server.use(bodyParser.json)
  server.delete('*', handle)
  server.get('*', handle)
  server.post('*', handle)
  server.put('*', handle)
  server.listen(8080)
})

/pages/api/test.js

export default (req, res) => {
  console.log(req.method, ' request')
  console.log(req.body)
  res.end()
}

curl http://localhost:8080/api/test

Expected behavior

To be able to use express with body-parser without conflicting with next.

System information

  • OS: Linux
  • Browser: any
  • Version of Next.js: 9.0.3

Additional context

I'm using passport with express and I need to have a body-parser to make it works.

Most helpful comment

Hey @soratobukuroneko, we parse body in default so there is no need to parse your body. If you want to disable body-parser you can do it by adding config to your API routes like this:

export const config = {
  api: {
    bodyParser: false,
  },
}

All 3 comments

This is an extreme mess to make it work for my experience. Why don't you use the body parser included with Express? You should probably remove your custom server and do everything with the serverless API routes from next, also because I don't even think you we can use target: server once deployed anyway.

Hey @soratobukuroneko, we parse body in default so there is no need to parse your body. If you want to disable body-parser you can do it by adding config to your API routes like this:

export const config = {
  api: {
    bodyParser: false,
  },
}
export const config = {
  api: {
    bodyParser: false,
  },
}

if you turn off the body parser then - heroku h18

2020-04-29T10:54:59.950106+00:00 heroku[router]: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/api/upload" host=eeeman-masterclass.herokuapp.com request_id=f2944ca2-0ba2-40ab-9064-5b1cff6933e0 fwd="109.252.129.15" dyno=web.1 connect=1ms service=141ms status=503 bytes=180 protocol=https

Was this page helpful?
0 / 5 - 0 ratings

Related issues

havefive picture havefive  路  3Comments

wagerfield picture wagerfield  路  3Comments

sospedra picture sospedra  路  3Comments

knipferrc picture knipferrc  路  3Comments

swrdfish picture swrdfish  路  3Comments