
- Next.js - Home
- Next.js - Overview
- Next.js - Project Setup
- Next.js - Folder Structure
- Next.js - App Router
- Next.js - Page Router
- Next.js Features
- Next.js - Pages
- Next.js - Data Fetching
- Next.js - ISR
- Next.js - Static File Serving
- Next.js - Pre-Rendering
- Next.js - Partial Pre Rendering
- Next.js - Server Side Rendering
- Next.js - Client Side Rendering
- Next.js Routing
- Next.js - Routing
- Next.js - Nested Routing
- Next.js - Dynamic Routing
- Next.js - Parallel Routing
- Next.js - Imperative Routing
- Next.js - Shallow Routing
- Next.js - Intercepting Routes
- Next.js - Redirecting Routes
- Next.js - Navigation and Linking
- Next.js Configuration
- Next.js - TypeScript
- Next.js - Environment Variables
- Next.js - File Conventions
- Next.js - ESLint
- Next.js API & Backend
- Next.js - API Routes
- Next.js - Dynamic API Routes
- Next.js - Route Handlers
- Next.js - API MiddleWares
- Next.js - Response Helpers
- Next.js API Reference
- Next.js - CLI Commands
- Next.js - Functions
- Next.js - Directives
- Next.js - Components
- Next.js - Image Component
- Next.js - Font Component
- Next.js - Head Component
- Next.js - Form Component
- Next.js - Link Component
- Next.js - Script Component
- Next.js Styling & SEO
- Next.js - CSS Support
- Next.js - Global CSS Support
- Next.js - Meta Data
- Next.js Advanced Topics
- Next.js - Error Handling
- Next.js - Server Actions
- Next.js - Fast Refresh
- Next.js - Internationalization
- Next.js - Authentication
- Next.js - Session Management
- Next.js - Authorization
- Next.js - Caching
- Next.js - Data Caching
- Next.js - Router Caching
- Next.js - Full Route Caching
- Next.js - Request Memoization
- Next.js Performance Optimization
- Next.js - Optimizations
- Next.js - Image Optimization
- Next.js - Lazy Loading
- Next.js - Font Optimization
- Next.js - Video Optimization
- Next.js - Script Optimization
- Next.js - Memory Optimization
- Next.js - Using OpenTelemetry
- Next.js - Package Bundling Optimization
- Next.js Testing
- Next.js - Testing
- Next.js - Testing with Jest
- Next.js - Testing with Cypress
- Next.js - Testing with Vitest
- Next.js - Testing with Playwright
- Next.js Debugging & Deployment
- Next.js - Debugging
- Next.js - Deployment
- Next.js Useful Resources
- Next.js - Interview Questions
- Next.js - Quick Guide
- Next.js - Useful Resources
- Next.js - Discussion
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:

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.
