Next.js Discord

Discord Forum

Handling both POST and GET req in the same route

Unanswered
Northern Wheatear posted this in #help-forum
Open in Discord
Northern WheatearOP
I'm trying to implment a route which can handle both POST and GET requests in the same route. I can do it with route.tsx but then I would loose the layout and contexts. So I need to use page.tsx for this but then I can't use it to handle POST req. Can someone help me with this?

5 Replies

@Northern Wheatear I'm trying to implment a route which can handle both POST and GET requests in the same route. I can do it with route.tsx but then I would loose the layout and contexts. So I need to use page.tsx for this but then I can't use it to handle POST req. Can someone help me with this?
export default async function yourFunction(req: NextApiRequest, res: NextApiResponse) {
  // Do whatever you want here
  return ...
}

export { yourFunction as GET, yourFunction as POST };

Like that you can create both: GET and POST to one function
Northern WheatearOP
Yes I can do this in route.tsx but I need it in page.tsx
I need to display an actual page as well as use the same route to handle POST requests also
@Northern Wheatear I need to display an actual page as well as use the same route to handle POST requests also
page.tsx can't handle POST requests. If you tell a little more about what you are trying to archive, I may be able to help you more
@Northern Wheatear can u tell me more?