How do you handle different HTTP methods such as GET, POST, and DELETE within a single API route file?
Short answer
You check the req.method value at the top of your handler function and run different logic depending on whether the request is a GET, POST, or DELETE, returning an appropriate response or an error status for methods you do not support.
Advertisement
AModel answer
You check the req.method value at the top of your handler function and run different logic depending on whether the request is a GET, POST, or DELETE, returning an appropriate response or an error status for methods you do not support.
export default function handler(req, res) {
if (req.method === 'POST') {
return res.status(201).json({ created: true });
}
if (req.method === 'GET') {
return res.status(200).json({ items: [] });
}
res.status(405).json({ error: 'Method not allowed' });
}Real-world example
A todo list API route supports GET to fetch tasks and POST to create new ones, all handled cleanly inside one file based on the incoming request method.
Likely follow-ups
- What status code should you return for unsupported methods?
- How do you add authentication checks to an API route?
Related topics