Next.js - Dynamic API Routes



In this chapter, we will learn about dynamic API Routes in Next.js, how to create a dynamic API route, handle different HTTP methods, and fetch data based on dynamic parameters.

Dynamic API Routes in Next.js

Dynamic API Routes in Next.js are used to create API routes that can handle dynamic parameters in the URL such as IDs, slugs, or user-specific data. These routes are defined using square brackets ([param]) in the file name. The dynamic API routes enable you to define dynamic server-side logic that can be called from the frontend or any external client.

How it Works?

  • Dynamic API Routes in Next.js are created by adding a file with square brackets ([param]) inside the 'pages/api' directory.
  • The square brackets are used to define dynamic parameters in the URL.
  • Any file inside the folder 'pages/api' with square brackets is mapped to /api/* and will be treated as a dynamic API endpoint instead of a page.
  • For example, if you create a file named '[id].js' inside the 'pages/api/user' directory, the endpoint will be '/api/user/[id]', where [id] represents any user ID.

Create a Dynamic API Route

Let's create a simple dynamic API route that fetches data based on a dynamic parameter. Create a file named '[id].js' inside the 'pages/api/user' directory with the following code:

// File: pages/api/user/[id].js

export default function handler(req, res) {
    const { id } = req.query; // Access dynamic parameter
    res.status(200).json({ message: `Fetching data for user ${id}` });
}

Output

Now, if you visit the URL 'pages/api/user/[id]' (choose a custom ID), you will see the following JSON response:

Next.js Dynamic API Routes

Handle HTTP Methods

Dynamic API Routes in Next.js can handle different HTTP methods like GET, POST, PUT, DELETE, etc. Any Next.js component can call the API route using different methods. The API route can return different responses based on the method used.

Example

In the following code below, we have created a dynamic API route (pages/api/user/[id].js) that handles different HTTP methods. The route returns a different message based on the method used. Then we defined a Next.js component (pages/display-data/index.js) that calls the API route using different methods.

// File: pages/api/user/[id].js

export default function handler(req, res) {
    const { id } = req.query; // Access dynamic parameter
  
    if (req.method === 'GET') {
        res.status(200).json(
            { message: `Fetching details for user ${id}` }
        );
    } 
    else if (req.method === 'DELETE') {
        res.status(200).json(
            { message: `User ${id} deleted successfully` }
        );
    } 
    else {
        res.setHeader('Allow', ['GET', 'DELETE']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
    }
  }

// File: pages/display-data/index.js

import { useState } from 'react';

export default function UserComponent() {
  const [userId, setUserId] = useState('');
  const [responseMessage, setResponseMessage] = useState('');

  // Function to fetch user details (GET request)
  const fetchUserDetails = async () => {
    try {
      const response = await fetch(`/api/user/${userId}`);
      const data = await response.json();
      setResponseMessage(data.message);
    } catch (error) {
      setResponseMessage('Failed to fetch user details.');
    }
  };

  // Function to delete user (DELETE request)
  const deleteUser = async () => {
    try {
      const response = await fetch(`/api/user/${userId}`, 
                                    { method: 'DELETE' });
      const data = await response.json();
      setResponseMessage(data.message);
    } 
    catch (error) {
      setResponseMessage('Failed to delete user.');
    }
  };

  return (
    <div>
        <h1>User API Interaction</h1>

        <input
            type="text"
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
        />
        <button onClick={fetchUserDetails}>
            Fetch User Details
        </button>
        <button onClick={deleteUser}>
            Delete User
        </button>

        {responseMessage && <p>{responseMessage}</p>}
    </div>
  );
}

Output

Now, if you visit the URL 'pages/display-data/index.js' and enter a user ID, you can fetch user details or delete the user based on the method used. The HTTP requests made are visible in chrome dev tools.

Next.js Dynamic API Routes All Methods
Advertisements