Dynamic API Routes
Dynamic API routes in Next.js allow you to create flexible endpoints that handle dynamic parameters in the URL. This is useful for building APIs that require variable data, such as fetching specific resources based on IDs or filtering data based on query parameters. Here’s how you can create dynamic API routes in Next.js:
- Define Dynamic Route File: Inside the `pages/api` directory, create a JavaScript file with square brackets `[]` in the filename. For example, `pages/api/users/[id].js` will create a dynamic API route that accepts `id` as a parameter.
- Access Dynamic Parameters: In the dynamic route file, export a default function (`handler`) that takes `req` (request) and `res` (response) as arguments. Inside this function, you can access dynamic parameters from the URL using `req.query` or `req.params` depending on the route structure.
- Handle Dynamic Data: Use the dynamic parameter received in the request to fetch specific data, perform operations, or customize the response based on the dynamic input.
Here’s an example of a dynamic API route in Next.js that handles a user ID parameter:
// pages/api/users/[id].js
export default function handler(req, res) {
const { id } = req.query; // Access dynamic parameter "id"
// Use the id to fetch user data from a database or an external API
const userData = { id, name: 'John Doe', email: 'john@example.com' };
// Send back the user data as a JSON response
res.status(200).json(userData);
}
In this example, visiting `/api/users/123` in your Next.js application will trigger this API route, and it will respond with a JSON object containing the user data for ID 123.
How to use Next.js API Routes?
Next.js API Routes are a feature of Next.js that allows you to create server-side logic and APIs within your Next.js application. These API routes are implemented using files in the `pages/api` directory of your Next.js project. When you deploy your Next.js application, these API routes are automatically served as serverless functions.
Table of Content
- Key points about Next.js API Routes
- Dynamic API Routes
- Creating an API Route
- API Routes custom configuration
- Typing API Routes with TypeScript
- Accessing an API Route
- Conclusion