Working with API Routes in Next.js


Introduction

Next.js is a powerful framework that simplifies server-side and API development. API routes in Next.js allow you to build robust and efficient backend functionality for your web applications. In this tutorial, we'll explore the concept of API routes and create sample API endpoints using Next.js.


Setting Up the Project

Before we dive into API routes, let's set up a new Next.js project. Ensure you have Node.js and npm installed on your system. If not, download and install them from the official website.


Create a new Next.js project using the following commands:


        npx create-next-app api-example
cd api-example

Creating an API Route

API routes in Next.js are special routes that are used for handling backend logic. These routes reside in the `pages/api` directory. Let's create a simple API route to retrieve a list of items.


        // pages/api/items.js
export default function handler(req, res) {
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
];
res.status(200).json(items);
}

In the code above, we've created an API route named `items`. This route responds with a JSON array of items when accessed.


Accessing the API Route

You can access the API route we've created by making a GET request to the route's URL. In a real project, you can use tools like Axios, Fetch, or any HTTP library to fetch data from your API routes. For this example, let's create a simple HTML page that fetches and displays the items.


        <!-- pages/index.js -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>API Route Example</title>
</head>
<body>
<h1>Items</h1>
<ul id="item-list"></ul>
<script>
async function fetchItems() {
const response = await fetch('/api/items');
const items = await response.json();
const itemList = document.getElementById('item-list');
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item.name;
itemList.appendChild(li);
});
}
fetchItems();
</script>
</body>
</html>

In this HTML page, we use JavaScript to make a GET request to our `items` API route and display the items in an unordered list.


Conclusion

Next.js API routes provide a powerful way to build backend logic for your applications. This tutorial covers the basics of creating API routes and accessing them from a simple HTML page. In a real-world scenario, you can implement more complex logic, handle different HTTP methods, and integrate with databases or external services.