0
0
NextJSframework~30 mins

Dynamic API routes in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Dynamic API Routes in Next.js
📖 Scenario: You are building a simple Next.js API that returns user information based on a user ID provided in the URL. This is common when you want to fetch data dynamically for different users.
🎯 Goal: Create a dynamic API route in Next.js that reads the userId from the URL and returns a JSON response with the user's details.
📋 What You'll Learn
Create a data object with user details keyed by user IDs
Add a variable to hold the user ID parameter from the request
Write the API handler function that returns user data based on the user ID
Export the API handler as default from the dynamic route file
💡 Why This Matters
🌍 Real World
Dynamic API routes let you build flexible backend endpoints that respond to different inputs in the URL, such as user profiles, product details, or blog posts.
💼 Career
Understanding dynamic API routes is essential for building modern web applications with Next.js, enabling you to create scalable and maintainable server-side logic.
Progress0 / 4 steps
1
Create user data object
Create a constant object called users with these exact entries: '1': { name: 'Alice', age: 25 }, '2': { name: 'Bob', age: 30 }, and '3': { name: 'Charlie', age: 35 }.
NextJS
Need a hint?

Use a JavaScript object with string keys for user IDs and objects for user details.

2
Get userId from request query
Add a constant called userId that extracts userId from req.query inside the API handler function.
NextJS
Need a hint?

Use object destructuring to get userId from req.query.

3
Return user data or 404
Inside the handler function, write code that checks if users[userId] exists. If yes, respond with status 200 and JSON of the user data. If not, respond with status 404 and JSON message { error: 'User not found' }.
NextJS
Need a hint?

Use if to check user existence and res.status().json() to send responses.

4
Export the handler as default
Ensure the API handler function is exported as the default export from the file using export default function handler(req, res) { ... }.
NextJS
Need a hint?

The function must be exported as default for Next.js API routing to work.