Dynamic Routes with Example
In real-world applications, we often need to create web pages that respond differently based on the data passed in the URL. That’s exactly where dynamic routes come in!
What Are Routes?
In a web app, when a user visits a specific URL, we use a route to handle that request.
Example:
app.get("/about", (req, resp) => {
resp.send("About Page");
});
This route handles requests made to localhost:3200/about
.
What Are Dynamic Routes?
Dynamic routes allow us to pass dynamic data through the URL using parameters.
Instead of writing a new route for every user, we write one route that accepts any user name as a parameter.
Creating a Dynamic User Profile Page
Create a List of Users with Profile Links
app.get("/", (req, resp) => {
const users = ["anil", "sam", "peter", "sidhu"];
let data = `<ul>`;
for (let i = 0; i < users.length; i++) {
data += `<li><a href="/user/${users[i]}">${users[i]}</a></li>`;
}
data += `</ul>`;
resp.send(data);
});
- This will render a list of user names as links like:
/user/anil
/user/sam
Create a Dynamic Route to Handle User Profile
app.get("/user/:name", (req, resp) => {
const userName = req.params.name;
resp.send(`This is ${userName}'s Profile Page`);
});
- Here,
:name
is a dynamic parameter. req.params.name
captures whatever is passed in the URL.
How It Works:
- Visiting
/user/anil
will display: - "This is anil's Profile Page"
- Visiting
/user/sidhu
will display: - "This is sidhu's Profile Page"
This is super useful for applications like:
- Blog posts (
/post/:id
) - User profiles (
/user/:username
) - Product pages (
/product/:slug
)