Dynamic Route Segments
What you'll learn: How to create flexible routes that extract variable parts from URLs to display different content without needing separate routes for each item.
The Core Idea
Imagine you're building a user profile page. Instead of creating routes like /users/alice, /users/bob, /users/charlie separately, you define one route pattern: /users/:id. The :id part is a dynamic segment—a placeholder that matches any value and captures it for use in your code.
When someone visits /users/alice, your router extracts "alice" from the URL and makes it available to your route handler, which can then fetch and display Alice's profile. Same route pattern, different content.
How It Works
Dynamic segments are marked with a colon (:) followed by a parameter name:
const routes = {
'/users/:id': handleUserProfile,
'/posts/:postId/comments/:commentId': handleComment
};
When matching a URL like /users/42, your route matcher:
- Recognizes the pattern
/users/:id - Extracts
42as the value forid - Passes it to your handler:
handleUserProfile({ id: '42' })
function handleUserProfile(params) {
const userId = params.id; // "42"
// Fetch and display user data for ID 42
}
You can have multiple dynamic segments in one route, like /posts/:postId/comments/:commentId, extracting both IDs from the URL path.
Why This Matters
Without dynamic segments, you'd need hardcoded routes for every possible user, product, or article—impossible for real applications. Dynamic segments let you build scalable routes that handle unlimited variations with minimal code.
Key Takeaway: Dynamic route segments use :paramName placeholders to capture variable parts of URLs, enabling one route pattern to serve infinite variations of content.