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);
});
  1. 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`);
});
  1. Here, :name is a dynamic parameter.
  2. req.params.name captures whatever is passed in the URL.


How It Works:

  1. Visiting /user/anil will display:
  2. "This is anil's Profile Page"
  3. Visiting /user/sidhu will display:
  4. "This is sidhu's Profile Page"

This is super useful for applications like:

  1. Blog posts (/post/:id)
  2. User profiles (/user/:username)
  3. Product pages (/product/:slug)