Next.js is a powerful React framework that allows developers to build server-rendered and statically generated web applications easily. One of its key features is the ability to create API routes, which allows you to build a full-fledged backend within a Next.js app. In this guide, we'll explore how to create and use API routes in Next.js, with practical examples to help you understand the process.
API routes in Next.js allow you to create server-side endpoints to handle requests like form submissions, database queries, or external API calls. These routes live in the `/pages/api` directory and can respond to HTTP methods such as `GET`, `POST`, `PUT`, `DELETE`, etc.
Let’s start with a basic example of creating an API route in Next.js. The API route will simply return a JSON response with a message.
api
inside the pages
directory if it doesn’t exist already.
pages/api
folder, create a new file named hello.js
. This file will define the API route.
hello.js
file:
export default function handler(req, res) {
res.status(200).json({ message: "Hello, World!" });
}
In this example, the handler
function takes two arguments: req
(the request object) and res
(the response object). It sends a response with status code 200 and a JSON object containing the message "Hello, World!".
Once you’ve created the API route, you can access it by visiting http://localhost:3000/api/hello
while running your Next.js app. You should see a response like this:
{
"message": "Hello, World!"
}
In Next.js API routes, you can handle different HTTP methods like GET
, POST
, PUT
, and DELETE
in a single route. Here’s an example that demonstrates how to handle multiple HTTP methods.
Let’s extend the previous example to handle both GET
and POST
requests. We’ll respond with a message for GET
requests and echo back the data sent in a POST
request.
export default function handler(req, res) {
if (req.method === "GET") {
res.status(200).json({ message: "You sent a GET request" });
} else if (req.method === "POST") {
const { name } = req.body;
res.status(200).json({ message: `Hello, ${name}!` });
} else {
res.status(405).json({ message: "Method Not Allowed" });
}
}
In this example:
GET
request returns a simple message.POST
request expects a JSON body with a name
property and responds with a greeting.GET
or POST
is used, the API returns a 405 (Method Not Allowed) status code.You can interact with your API route using the Fetch API from the client side. Here’s an example of calling the above API route from a React component in Next.js.
import { useState } from "react";
export default function MyComponent() {
const [name, setName] = useState("");
const [responseMessage, setResponseMessage] = useState("");
const handleSubmit = async () => {
const res = await fetch("/api/hello", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ name }),
});
const data = await res.json();
setResponseMessage(data.message);
};
return (
setName(e.target.value)}
placeholder="Enter your name"
/>
{responseMessage}
);
}
In this component:
/api/hello
route using a POST
request.
By default, Next.js doesn't parse the body of incoming requests. For JSON, you can use req.body
directly if the request includes the correct Content-Type
header (`application/json`). For other types of content (like form data), you need to manually handle the parsing.
As shown in the previous examples, the request body is automatically parsed as JSON if the correct headers are set:
export default function handler(req, res) {
if (req.method === "POST") {
const { name } = req.body; // Parsed automatically
res.status(200).json({ message: `Hello, ${name}!` });
}
}
To handle URL-encoded form data (i.e., when forms are submitted with application/x-www-form-urlencoded
), you need to manually parse the request body. Here’s an example:
import { parse } from 'querystring';
export default function handler(req, res) {
if (req.method === "POST") {
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // Convert Buffer to string
});
req.on('end', () => {
const parsedBody = parse(body); // Parse URL-encoded body
res.status(200).json({ message: `Hello, ${parsedBody.name}!` });
});
}
}
When creating API routes, it's essential to consider security best practices:
API routes in Next.js are a powerful feature that enables you to build robust server-side logic alongside your React components. Whether you need to handle simple form submissions, fetch data from external APIs, or perform complex database operations, API routes provide a flexible way to integrate backend functionality into your Next.js app. With this guide, you should now have a solid foundation for working with API routes in Next.js.