LibraryDynamic API routes and route parameters

Dynamic API routes and route parameters

Learn about Dynamic API routes and route parameters as part of Next.js 14 Full-Stack Development

Dynamic API Routes and Route Parameters in Next.js 14

In full-stack web development, especially with frameworks like Next.js, APIs are crucial for handling data and logic. Dynamic API routes allow you to create flexible endpoints that can respond to varying parts of a URL, making your applications more robust and scalable. This module focuses on understanding and implementing dynamic API routes and route parameters in Next.js 14.

What are Dynamic API Routes?

Traditional API routes in Next.js are static, meaning each route maps to a specific file. Dynamic API routes, on the other hand, use a file-system-based routing system that allows you to create endpoints whose paths are determined at runtime. This is achieved by enclosing folder names in square brackets, like

code
[slug]
or
code
[id]
.

Understanding Route Parameters

When a dynamic route is matched, the values within the brackets are captured as route parameters. These parameters are accessible within your API route handler functions. For example, if you have a route

code
pages/api/users/[id].js
, and a request comes in for
code
/api/users/123
, the
code
id
parameter will have the value
code
123
.

Route parameters enable flexible API endpoints.

Dynamic routes use bracketed folder names (e.g., [param]) to capture parts of the URL as parameters. These parameters are then available in your API handler.

In Next.js, dynamic API routes are defined by creating files within folders named with square brackets. For instance, a file structure like pages/api/products/[productId].js will create a dynamic API route. When a request is made to /api/products/abc-123, the productId parameter will be accessible within the API handler with the value abc-123. This allows you to build APIs that can serve data based on specific identifiers or slugs, such as fetching a particular product or user profile.

Accessing Route Parameters in API Handlers

Within your API route handler (e.g.,

code
pages/api/users/[id].js
), you can access route parameters through the
code
req.query
object. The
code
req.query
object contains all query string parameters and route parameters.

Consider an API route defined at pages/api/posts/[slug].js. A request to /api/posts/my-first-post will result in req.query.slug being equal to 'my-first-post'. This allows you to dynamically fetch data based on the provided slug. The req object in your API handler contains a query property, which is an object holding these parameters. For example, req.query.slug would give you the value from the URL.

📚

Text-based content

Library pages focus on text content

Example: Fetching a Specific User

Let's illustrate with an example. Suppose you have a file

code
pages/api/users/[userId].js
:

javascript
// pages/api/users/[userId].js
export default function handler(req, res) {
const { userId } = req.query;
// In a real application, you would fetch user data from a database
// based on the userId.
const userData = {
id: userId,
name: `User ${userId}`,
email: `user${userId}@example.com`
};
res.status(200).json(userData);
}

When you make a GET request to

code
/api/users/42
, the
code
userId
parameter will be
code
42
, and the API will return JSON data for that user.

Catch-all Routes

Next.js also supports catch-all routes using

code
[...slug]
. This allows you to match any path within a directory. For example,
code
pages/api/files/[...slug].js
would match
code
/api/files/a
,
code
/api/files/a/b
, and so on. The
code
slug
parameter would then be an array of the path segments.

How do you define a dynamic API route in Next.js?

By creating a folder with square brackets around the name, e.g., [paramName].

Where can you access route parameters within an API handler?

In the req.query object.

Integrating with the Frontend

On the frontend, you can use the

code
useRouter
hook from
code
next/router
to access route parameters for dynamic page routes, and then use these parameters to make API calls to your dynamic API endpoints. This creates a seamless full-stack experience where your frontend and backend routes are interconnected.

Dynamic API routes are powerful for creating RESTful APIs that respond to specific resource identifiers, enhancing the flexibility and reusability of your backend.

Learning Resources

Dynamic API Routes - Next.js Documentation(documentation)

The official Next.js documentation on dynamic routing, covering both page and API routes. Essential for understanding the core concepts.

API Routes - Next.js Documentation(documentation)

Comprehensive guide to creating API routes in Next.js, including how to handle requests and responses.

Next.js 13 API Routes Tutorial(video)

A video tutorial demonstrating how to build API routes in Next.js, often covering dynamic routes as a key feature.

Understanding Next.js API Routes(blog)

A blog post explaining the fundamentals of Next.js API routes, with practical examples that may include dynamic routing.

Mastering Next.js API Routes(video)

An in-depth video guide to Next.js API routes, likely covering dynamic parameters and advanced usage.

Next.js Dynamic Routes Explained(video)

A focused video tutorial specifically explaining dynamic routing in Next.js, which applies to API routes as well.

How to Use Dynamic Routes in Next.js(blog)

A tutorial from DigitalOcean that breaks down dynamic routing in Next.js, providing clear examples.

Next.js API Routes: A Complete Guide(blog)

A comprehensive blog post covering various aspects of Next.js API routes, including how to handle dynamic parameters.

Next.js Catch-all Routes(documentation)

Specific documentation section on catch-all routes in Next.js, explaining how to use `[...slug]` for flexible API endpoints.

Building a Full-Stack App with Next.js(video)

A broader tutorial on building full-stack applications with Next.js, which will likely demonstrate the integration of dynamic API routes.