API Routes in Next.js are incredibly versatile, allowing you to build backend functionality directly within your Next.js application. One of the fundamental aspects of working with APIs is handling different HTTP methods. Each method signifies a distinct action on a resource: GET for retrieving data, POST for creating new data, PUT for updating existing data (or creating if it doesn't exist), and DELETE for removing data. Next.js makes it straightforward to implement logic for each of these methods within a single API route file.
Consider an API route located at pages/api/users/[id].js. This route can dynamically handle requests based on the user ID provided in the URL. We can implement separate logic for each HTTP method by exporting functions named after the method (e.g., export async function GET(req, res)). If a method is not explicitly handled, Next.js will respond with a 405 Method Not Allowed error.
import { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req, res) {
const { id } = req.query;
if (req.method === 'GET') {
// Logic to retrieve a specific user by ID
res.status(200).json({ id, message: `GET request for user ${id}` });
} else if (req.method === 'PUT') {
// Logic to update a specific user by ID
const updatedUserData = req.body;
res.status(200).json({ id, message: `PUT request for user ${id}`, data: updatedUserData });
} else if (req.method === 'DELETE') {
// Logic to delete a specific user by ID
res.status(200).json({ id, message: `DELETE request for user ${id}` });
} else {
// Handle other methods or respond with 405
res.setHeader('Allow', ['GET', 'PUT', 'DELETE']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}Alternatively, for simpler API routes that might only need to handle one or two methods, you can export specific functions for those methods directly. This often leads to cleaner and more readable code when you don't need to handle every possible HTTP verb.
import { NextApiRequest, NextApiResponse } from 'next';
export async function GET(req, res) {
const { id } = req.query;
// Logic to retrieve a specific user by ID
res.status(200).json({ id, message: `GET request for user ${id}` });
}
export async function POST(req, res) {
const newUserData = req.body;
// Logic to create a new user
res.status(201).json({ message: 'User created successfully', data: newUserData });
}