How to use different middlewares for get and post methods in Next js api?

Viewed 914

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.

1 Answers

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
Related