Using API routes in your project
Introduction
Next.js, a popular React framework, has built-in support for API routes. This feature allows you to create an API endpoint within your Next.js application. This can be useful for various reasons such as interacting with a database or handling form submissions. In this tutorial, we'll learn how to use API routes in your Next.js project.
What are API Routes
API routes provide a solution to build your API with Next.js. These API routes are server-side, meaning that they run on the server before anything is sent to the client. They reside in the pages/api
directory and are treated as separate entities from the rest of your Next.js application.
How to Create an API Route
Creating an API route in Next.js is simple. Let's create a simple API endpoint that returns a JSON response.
First, navigate to the
pages/api
directory in your Next.js project. If the directory doesn't exist, you can go ahead and create it.Inside the
api
directory, create a new file namedhello.js
.Open
hello.js
and add the following code:
export default function handler(req, res) {
res.status(200).json({ text: 'Hello' })
}
This function receives two arguments: req
(the request object) and res
(the response object). We set the status code to 200 (which means "OK") and send a JSON response with the text "Hello".
- Now, you can access this API endpoint in your browser by navigating to
http://localhost:3000/api/hello
. You should see the following result:
{"text":"Hello"}
Using Different HTTP Methods
Next.js API routes support all HTTP methods. You can specify a different method for your API route by checking req.method
in your API route function.
Let's modify our hello.js
API route to handle both GET and POST requests:
export default function handler(req, res) {
if (req.method === 'POST') {
res.status(200).json({ text: 'Hello POST' })
} else {
res.status(200).json({ text: 'Hello GET' })
}
}
With this code, if you send a POST request to http://localhost:3000/api/hello
, you'll receive {"text":"Hello POST"}
. If you send a GET request, you'll receive {"text":"Hello GET"}
.
Conclusion
Next.js API routes provide a straightforward solution to building server-side functionality into your Next.js apps. They're easy to set up and flexible, supporting all HTTP methods and allowing you to handle different types of requests in a single function.
This feature is a powerful addition to the Next.js framework, enabling developers to build full-stack applications using a single language (JavaScript) and framework (React and Next.js). By making use of API routes, you can simplify your development process and create more efficient, streamlined applications.