Open In App

Next JS Dynamic API Routes

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Dynamic API routes are the types of routes which are used to create the URL Path of an API with dynamic parameters and allows you to render different content on the UI based on the URL Path. If we need to define a large number API routes with different parameters, if number of routes to be defines exceeds 100 , 1000 and so on, then we cannot create them manually.

Prerequisites

How to declare Dynamic API Routes?

Dynamic API Routes in Next.js follows a pre-defined syntax to declare Dynamic API routes. To declare a Dynamic API routes in Next.js you need to write the file name or folder name in square brackets “[]”. then, write the code of the application in the function.

Syntax:

[folder_name] or [file_name].jsx 

Steps to create Dynamic API Routes in Next JS

Step 1: Create a NextJs app using the following command.

npx create-next-app my-app

Step 2 : Got to the project directory and create a main Folder students in “src/app” directory

cd my-app
src -> app -> new_folder_name = students

Step 3 : Create a new Folder with [studentId] inside students folder.

mkdir [studentId]

Step 4 : Create a new file inside [studentId]

example:/src/app/students/[studentId]/page.jsx

Project Structure:

fileName

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.0.4"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10.0.1",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"eslint": "^8",
"eslint-config-next": "14.0.4"
}

Example: Write the following code in page.jsx file.

Javascript




//page.jsx
 
//param object contains route paramters as KEY-VALUE pair
export default function Students({ params }) {
    return (
        <main >
            <div className="font-semibold text-xl ml-10 " >
        //Students List with different student Id
                <h3 className="font-bold text-2xl " > Students List </h3>
                I am Geek {params.studentId}
            </div>
        </main>
    )
}


Step To run the application:

Step 1: Run the following command in the terminal

npm run dev 

Test your dynamically created API routes by visiting “http://localhost:3000/students/1, http://localhost:3000/students/2, …. http://localhost:3000/students/1000, etc. ” in your browser

http://localhost:3000/students/1
http://localhost:3000/students/2
http://localhost:3000/students/3
..........
..........
..........
..........
http://localhost:3000/students/1000

Output: For different Dynamic API Path, It will generate a different content on UI to be rendered. Some of them are as shown below.

Animation17



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads