In this tutorial, we will be discussing how to handle different HTTP methods in Next.js API routes. API routes in Next.js allow you to build your API with serverless functions. With Next.js, the pages/api
directory is treated as an API endpoint, and files within this directory are mapped to /api/*
routes.
You will learn how to handle various HTTP methods like GET, POST, PUT, DELETE, etc. This will be beneficial in building full-fledged web applications with Next.js.
In Next.js, you can create an API route by creating a function inside the pages/api
directory. The function should export a default function, which will receive two arguments: req
(the request object) and res
(the response object).
Different HTTP methods can be handled in the API route handler function as follows:
export default function handler(req, res) {
// you can access method property from req object
const { method } = req;
switch(method) {
case 'GET':
// handle GET request
break;
case 'POST':
// handle POST request
break;
case 'PUT':
// handle PUT request
break;
case 'DELETE':
// handle DELETE request
break;
default:
res.setHeader('Allow', ['GET', 'POST', 'PUT', 'DELETE']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}
Let's create a simple API route that handles different HTTP methods.
Create a new file pages/api/user.js
and add the following code:
// pages/api/user.js
export default function handler(req, res) {
const { method } = req;
switch(method) {
case 'GET':
res.status(200).json({ user: 'John Doe' });
break;
case 'POST':
// Assume we are receiving JSON
const { username } = req.body;
res.status(200).json({ user: username });
break;
default:
res.setHeader('Allow', ['GET', 'POST']);
res.status(405).end(`Method ${method} Not Allowed`);
}
}
In this example, we handle GET and POST methods. For GET requests, we simply return a JSON response with a user object. For POST requests, we retrieve username from the request body and return it in the response. If any other method is used, we return a 405 'Method Not Allowed' status.
In this tutorial, we have learned how to handle different HTTP methods in Next.js API routes. We looked at how to handle GET, POST, PUT, DELETE methods and how to return a proper response for unsupported methods.
For further learning, you could look into handling different content types, error handling, and authentication in Next.js API routes.
Remember, practice is crucial for getting comfortable with new concepts. Happy coding!