Home > Enterprise >  Can you have multiple api routes in one file NextJS
Can you have multiple api routes in one file NextJS

Time:08-11

So I'm new to NextJS and am trying to learn the api. In the default hello.js file inside of the api folder there is an export default function which returns a json response. So now if I want to add another route would I have to create a seperate file for that or just add a function below to do so? I would like to just be able to add more functions to create more routes.

CodePudding user response:

Yes you can have dynamic api routes just like you can have dynamic pages!

From the docs

For example, the API route pages/api/post/[pid].js has the following code:

export default function handler(req, res) {
  const { pid } = req.query
  res.end(`Post: ${pid}`)
}

Now, a request to /api/post/abc will respond with the text: Post: abc.

So you could definitely have different functions based on the api route you are trying to get to. You could use a switch or whatever works for you.

The Next JS docs = https://nextjs.org/docs/api-routes/dynamic-api-routes

  • Related