Skip to main content

Creating an API route

In this tutorial, we will explore how to create an API route in the Next.js framework. This tutorial is particularly geared towards beginners, so don't worry if you're new to this - we'll go through each step in detail.

What are API Routes in Next.js?

API Routes in Next.js allow you to build your API with serverless functions, which are pieces of code that can be deployed and executed individually. These routes are stored inside the pages/api directory, and each file corresponds to a route.

Creating Your First API Route

Let's start by creating our first API route in Next.js.

  1. First, create a new file inside the pages/api directory. You can name the file whatever you like, but for this tutorial, let's call it hello.js.
mkdir pages/api
touch pages/api/hello.js
  1. Now, open the hello.js file that you've just created and add the following code:
export default function handler(req, res) {
res.status(200).json({ text: 'Hello' })
}

In the code above, we're exporting a function that handles requests and responses. The function receives two arguments: req (the request object) and res (the response object).

We're then using the res.status() method to send a response with a status code of 200, which means the request was successful. Lastly, we're using the res.json() method to send a JSON response.

  1. To test your API route, go to http://localhost:3000/api/hello in your browser. You should see the following JSON response:
{
"text": "Hello"
}

Congratulations! You've just created your first API route in Next.js.

Understanding the Request & Response Objects

The req and res objects are instances of http.IncomingMessage and http.ServerResponse, respectively. You can use all built-in methods and properties of these objects in your API route.

The req object contains information about the request, such as the HTTP headers, the method used to make the request (GET, POST, etc.), and any data sent with the request.

The res object is used to send a response to the client. You can use methods like res.status() to set the status code of the response, and res.json() to send a JSON response.

Conclusion

In this tutorial, we've learned how to create a simple API route in Next.js. This is just the beginning - there's much more you can do with API routes in Next.js, such as handling different types of requests, working with databases, and more. As you continue to explore Next.js, you'll become more comfortable with these concepts and be able to build more complex API routes. Happy coding!