Dynamic Routes and Route Parameters
Learn how to use dynamic routes and parameters in Express.js to create flexible and efficient APIs.
When building web applications, we often need routes that handle dynamic data. Take an e-commerce platform, for example: retrieving a user’s order details shouldn’t require creating a unique route for every possible order ID. That approach would be impractical and difficult to maintain. Instead, dynamic routing allows us to define a single, reusable route that extracts order IDs directly from the URL. This approach ensures our code remains flexible, scalable, and maintainable.
Now, let’s see how Express allows us to define these dynamic routes efficiently.
Setting up a dynamic route
Express.js allows us to define dynamic segments in route paths using a colon (:
) prefix. For example, a route like /users/:id
has a dynamic segment :id
, which acts as a placeholder for actual values in incoming requests—like /users/123
.
Express automatically extracts these values and makes them available through the req.params
object. In this case, req.params.id
would contain "123"
.
This makes it easy to build flexible, data-driven routes that respond to different users, products, or resource IDs without hardcoding every possible path.
Get hands-on with 1400+ tech skills courses.