Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Next.js 9 API route works on Get Request but not Post request #7960

Closed
zluo01 opened this issue Jul 14, 2019 · 26 comments · Fixed by #16169 · May be fixed by NOUIY/next.js#138
Closed

Next.js 9 API route works on Get Request but not Post request #7960

zluo01 opened this issue Jul 14, 2019 · 26 comments · Fixed by #16169 · May be fixed by NOUIY/next.js#138

Comments

@zluo01
Copy link

zluo01 commented Jul 14, 2019

Question about Next.js

I try to modified some of the api to use post instead of get.
I have request code like this with normal fetch

 const response = await fetch(`${process.env.SERVER}/api/lyric?id=${song.song_id}`);

It will get to the file inside ./page/api and resolve, however, if I change to code to following

 const response = await fetch(`${process.env.SERVER}/api/lyric`, {
                    method: 'POST',
                    body: JSON.stringify({id: song.song_id})
                });

It will give me 404 not found. I wonder what is the problem here ?

Thank you

@zluo01 zluo01 changed the title Next.js API route works on Get Request but not Post request Next.js 9 API route works on Get Request but not Post request Jul 14, 2019
@huv1k
Copy link
Contributor

huv1k commented Jul 14, 2019

Hey @zluo01, provide full reproduction, from your issue it's hard to guess what could be wrong. You can check integration test for POST.

@zluo01 zluo01 closed this as completed Jul 14, 2019
@colemahatmccreary
Copy link

Were you able to figure this out? The documentation for API routes is pretty minimal, and I'm also receiving a 404 response for POST requests sent to a route that worked fine for GET requests

@zluo01
Copy link
Author

zluo01 commented Jul 18, 2019

Were you able to figure this out? The documentation for API routes is pretty minimal, and I'm also receiving a 404 response for POST requests sent to a route that worked fine for GET requests

Sorry no, I use Get and put stuff inside headers instead and I do not have time to produce a full reproduction.

@stoplion
Copy link

stoplion commented Jul 24, 2019

Some documentation on handling POST would be useful

@timneutkens
Copy link
Member

@stoplion what would you like to have documented? Can you create an issue following the issue template for it?

@stoplion
Copy link

Sure

@TommySorensen
Copy link

TommySorensen commented Aug 15, 2019

I also see the 404 in our project with the following:

const res = await fetch('/api/bookings', {
  method: 'POST',
  body: JSON.stringify({ hungry: true }),
  headers: {
    'Content-Type': 'application/json',
  },
})
const data = await res.json()

It dosent matter what the content is in the api/bookings file. It will never be hit. I'm using now dev to run the project on localhost

Update
I found out that it worked fine with the now dev but it did not work with my server.js file due to i had not handled post requests. If you simply add a handler for post request, everything will work fine:

server.post('*', (req, res) => {
  return handle(req, res)
})

@huv1k
Copy link
Contributor

huv1k commented Aug 15, 2019

@TommySorensen this should be fixed in the latest canary

@dan-fein
Copy link

Was this ever answered? Is there a way to POST to a Next v9 API Route?

@TommySorensen
Copy link

Was this ever answered? Is there a way to POST to a Next v9 API Route?

Yes. Just posting to the api routes will work just fine. Use this example and change the get to post. Thats what i did. Worked like a charm 😉

@lifeiscontent
Copy link
Contributor

@huv1k any idea on a release?

@huv1k
Copy link
Contributor

huv1k commented Aug 17, 2019

@lifeiscontent release of what?

@lifeiscontent
Copy link
Contributor

@huv1k on when the next release of next.js will come out with this fix

@TommySorensen
Copy link

@lifeiscontent There is no bug to fix. I tested it my self. POST work just fine if you use of the NextJS examples. It's properly something in your application. Please provide example of the full code, so we can help with the investigation 👍

@maddhruv
Copy link

easy deasy
in your custom server
do

server.use((req, res) => app.getRequestHandler()(req, res))

@thgh
Copy link

thgh commented Oct 16, 2019

Repro:

npx create-next-app --example with-firebase-authentication with-firebase-authentication-app

Add file api/test.js

export default (req, res) => {
  console.log('api test', req.method)
  res.json('ok')
}

Add request handler in server.js:

server.use((req, res) => app.getRequestHandler()(req, res))

Run yarn dev (or node server.js)

Send POST to http://localhost:3000/api/test

Expected: console logs api test POST
Actual: no logs, request stays pending until timeout

@zluo01 zluo01 reopened this Oct 16, 2019
@Timer
Copy link
Member

Timer commented Oct 16, 2019

You need to update the example:

  server.get('*', (req, res) => {
    return handle(req, res)
  })

needs to be:

  server.all('*', (req, res) => {
    return handle(req, res)
  })

@Timer Timer closed this as completed Oct 16, 2019
@thgh
Copy link

thgh commented Oct 17, 2019

Found our mistake: upgrading isomorphic-unfetch => DO NOT UPGRADE 🤕

By the way, Firebase dependency is quite old:

 firebase             ^5.6.0  →    ^7.2.1
 firebase-admin       ^5.8.2  →    ^8.6.1

@epranka
Copy link

epranka commented Dec 18, 2019

If anyone has this issue yet with a custom express server, it can occur while using multiple body parsers, because NextJs api routes enables it by default. Use only express body parser, or only NextJs body parser. How to disable NextJs body parser documented there: https://nextjs.org/docs#api-middlewares

@rscotten
Copy link
Contributor

rscotten commented Dec 31, 2019

@epranka @thgh, Man, it took me hours to figure this one out.

I'm using the Firebase Cloud Functions server, and I couldn't make any POST requests to my API route. POST requests would hang, but GET requests would work fine. And if I was using the local NextJS dev server, POST requests would also work fine.

Disabling the body parser when using Firebase Cloud Functions fixed it.

Apparently Firebase Cloud Functions comes with its own body parser, and it conflicts with the NextJS one. So you have to disable the body parser for Firebase Cloud Functions, but enable it for local development using the NextJS dev server.

So basically drop this in your pages/api/[yourEndPoint].js:

export const config = {
  api: {
    bodyParser: process.env.NODE_ENV !== 'production'
  }
};

@cooervo
Copy link

cooervo commented Jan 30, 2020

@TommySorensen answer solved it for me:

  server.get("*", (req, res) => handle(req, res));
  server.post("*", (req, res) => handle(req, res));

Many thanks!

@amardeepsingh20
Copy link

@epranka @thgh, Man, it took me hours to figure this one out.

I'm using the Firebase Cloud Functions server, and I couldn't make any POST requests to my API route. POST requests would hang, but GET requests would work fine. And if I was using the local NextJS dev server, POST requests would also work fine.

Disabling the body parser when using Firebase Cloud Functions fixed it.

Apparently Firebase Cloud Functions comes with its own body parser, and it conflicts with the NextJS one. So you have to disable the body parser for Firebase Cloud Functions, but enable it for local development using the NextJS dev server.

So basically drop this in your pages/api/[yourEndPoint].js:

export const config = {
  api: {
    bodyParser: process.env.NODE_ENV !== 'production'
  }
};

Thanks! Was facing the exact same issue. Resolved with your fix. Its surprising that Firebase functions do not give any config to turn off automatic body parsing.

@rohit267
Copy link

rohit267 commented Nov 4, 2020

so we have to use custom server, got it but getting the parsed body inside api route would have solved many problems.

kodiakhq bot pushed a commit that referenced this issue Dec 7, 2020
…16169)

## Why

Some users prefer to use a custom server implementation that handles body parsing. If they do this, they have no way to opt out of all body parsing in API Routes. Requests with bodies die if next's `bodyParser` is not disabled. Requests just hang forever.

Instead of adding [this config](https://nextjs.org/docs/api-routes/api-middlewares#custom-config) to every API Route, we do a simple check to avoid parsing the body twice.

Fixes #8315
Fixes #7960
@OZZlE
Copy link

OZZlE commented Apr 13, 2021

We had in our ExpressJs server.js this: server.use(bodyParser.json()) which made all POST request return 504 and not even log any console.log, because we didn't know about Next.js Api routes (weird name for Controller/BE)

Changed it to be route specific: https://github.com/expressjs/body-parser#express-route-specific and then it works :)

@SonicCodes
Copy link

I also see the 404 in our project with the following:

const res = await fetch('/api/bookings', {
  method: 'POST',
  body: JSON.stringify({ hungry: true }),
  headers: {
    'Content-Type': 'application/json',
  },
})
const data = await res.json()

It dosent matter what the content is in the api/bookings file. It will never be hit. I'm using now dev to run the project on localhost

Update
I found out that it worked fine with the now dev but it did not work with my server.js file due to i had not handled post requests. If you simply add a handler for post request, everything will work fine:

server.post('*', (req, res) => {
  return handle(req, res)
})

Hmm, I wonder why no one gave attention to that (get -> get, post -> post) 😆 , thanks, you saved my day.

@balazsorban44
Copy link
Member

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@vercel vercel locked as resolved and limited conversation to collaborators Jan 28, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet