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 separate 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.
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 separate 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.
2 Answers
Reset to default 4Yes 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.
Docs
i think you want to have different http method for an api route, right
you can with check method
export default function handler(req, res) {
if (req.method === 'POST') {
// Process a POST request
} else {
// Handle any other HTTP method
}
}