DEV Community

Cover image for Getting Started with Next.js: Part 3 - API Routes
Dipak Ahirav
Dipak Ahirav

Posted on

Getting Started with Next.js: Part 3 - API Routes

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:
     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:
     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:
     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.

Top comments (3)

Collapse
 
jenesh profile image
Jenesh Napit

Is the fetch imported or is avaliable without import?

Collapse
 
dipakahirav profile image
Dipak Ahirav

No, you don't need to add an import statement for the fetch API when using it in Next.js for client-side data fetching, as it is a browser-based API available globally in the browser environment. Your current code for the HomePage component is correct as it stands for use within a Next.js application that renders on the client-side. If your code runs on the server (for example, in getServerSideProps or other server-side functions), and you need to make HTTP requests, you might consider using Node.js compatible libraries like axios or node-fetch, which would require an import. But for client-side usage like in your component, no import statement for fetch is necessary.

Collapse
 
dipakahirav profile image
Dipak Ahirav

Next Part - PART - 4