2

With express we can use different middlewares for get and post requests, eg.

// GET method route
app.get('/users', function (req, res) {
    // handle get request
})
    
// POST method route
app.post('/users', auth, function (req, res) {
    // handle post request
})

How do I do the same in next js.

I am totally new to next js. I might be simply missing something.

Mattia Righetti
  • 1,265
  • 1
  • 18
  • 31

1 Answers1

5

To handle different HTTP methods in an API route, you can use req.method in your request handler.

export default function handler(req, res) {
  if (req.method === 'POST') {
    // Process a POST request
  } else {
    // Handle any other HTTP method
  }
}

Or you can use a package like next-connect which enables expressjs like API. In your api file:

import nc from "next-connect";

const handler = nc()
  .use(someMiddleware())
  .get((req, res) => {
    res.send("Hello world");
  })
  .post((req, res) => {
    res.json({ hello: "world" });
  })
  .put(async (req, res) => {
    res.end("async/await is also supported!");
  })
  .patch(async (req, res) => {
    throw new Error("Throws me around! Error can be caught and handled.");
  });
export default handler
Ivan V.
  • 7,593
  • 2
  • 36
  • 53
  • In the `next-connect` example the `someMiddleware` will be used among all methods which does not answer the question – Hairi Mar 15 '22 at 15:47
  • @Hairi I've given examples of different HTTP methods, and also an example with `someMiddleware` to demonstrate the usage on one middleware with all the methods. – Ivan V. Mar 15 '22 at 19:26