Getting Started with Next.js: Part 3 - API Routes
Tags: nextjs, javascript, beginners, programming
Published: 2024-04-29 02:36:25

## 🚀 Check Out My YouTube Channel! 🚀
Hi everyone! If you enjoy my content here on Dev.to, please consider subscribing to my YouTube channel [devDive with Dipak](https://www.youtube.com/@DevDivewithDipak). I post practical full-stack development videos that complement my blog posts. Your support means a lot!

## Introduction
Welcome to Part 3 of our Next.js series! Today, we're diving into one of Next.js's powerful features—API Routes. This feature allows you to build and manage server-side API endpoints within your Next.js application. API routes are perfect for handling form submissions, interacting with databases, or integrating with external APIs directly from your Next.js app.

## What are API Routes?
In Next.js, API routes provide a solution to build backend APIs as part of your application. They are server-side routes where you can write server code directly in your Next.js project under the `pages/api` directory. Each file inside this directory is treated as an API endpoint.

## Step 1: Creating an API Route
Let’s create a simple API endpoint that returns a JSON response with user data.

### How to Create an API Endpoint
1. **Navigate to the Pages Directory**: Go to the `pages` directory in your Next.js project.
2. **Create an API Directory**: Inside `pages`, create a new directory called `api`.
3. **Add a New JavaScript File**:
   - Create a file named `user.js` inside the `pages/api` directory.
   - Write the following code in `user.js`:
     ```javascript
     export default function handler(req, res) {
       res.status(200).json({ name: 'John Doe', age: 30 })
     }
     ```
   - This code creates an API route that can be accessed via `/api/user` and returns a JSON object with user data.

## Step 2: Testing Your API Route
To see your API route in action, you’ll want to test it:

1. **Start Your Development Server**:
   - If your server isn’t running, start it with:
     ```bash
     npm run dev
     ```
2. **Test the Endpoint**:
   - Open a web browser and navigate to `http://localhost:3000/api/user`.
   - You should see a JSON response `{ "name": "John Doe", "age": 30 }`.

## Step 3: Using API Routes in Your Application
API routes can be used to perform server-side operations. Here's how you can fetch data from your API route in a Next.js page:

1. **Edit an Existing Page or Create a New One**:
   - For example, update `pages/index.js`.
2. **Fetch Data from the API Route**:
   - Add the following code to get data from your API route when the component mounts:
     ```javascript
     import { useEffect, useState } from 'react';

     function HomePage() {
       const [userData, setUserData] = useState({});

       useEffect(() => {
         fetch('/api/user')
           .then(response => response.json())
           .then(data => setUserData(data));
       }, []);

       return (
         <div>
           <h1>Welcome to Next.js!</h1>
           <p>User Name: {userData.name}</p>
           <p>User Age: {userData.age}</p>
         </div>
       );
     }

     export default HomePage;
     ```
   - This example demonstrates how to fetch data from the server-side API and display it on the front end.

## Conclusion
API routes are a robust feature in Next.js that allow you to integrate server-side logic directly within your Next.js projects, making it easier to manage your full-stack applications. You’ve now learned how to create and use API routes, which can help you build more interactive and dynamic applications.

Stay tuned for Part 4, where we will explore more advanced topics in Next.js.