Skip to main content

Express Route Parameters

In the world of web development, static routes can only take you so far. Real-world applications often require creating URLs with dynamic parts that can change based on user input or other variables. This is where route parameters come in - they allow you to create flexible, dynamic routes in your Express applications.

What Are Route Parameters?

Route parameters are named URL segments used to capture values at specific positions in the URL. These captured values are stored in the req.params object, with the parameter names as their respective keys.

For example, in a URL like /users/123, the 123 part could be a route parameter representing a user ID.

Basic Syntax

In Express, route parameters are defined by prefixing a colon (:) to a segment in the route path:

javascript
app.get('/users/:userId', (req, res) => {
res.send(`User ID: ${req.params.userId}`);
});

In this example, :userId is a route parameter that will capture the value provided in that position of the URL.

Accessing Route Parameters

When a request is made to a route with parameters, Express extracts the values and stores them in the req.params object. Let's see a complete example:

javascript
const express = require('express');
const app = express();
const port = 3000;

app.get('/users/:userId', (req, res) => {
res.send(`You requested user with ID: ${req.params.userId}`);
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

If you make a request to /users/42, the server response would be:

You requested user with ID: 42

If you make a request to /users/john, the response would be:

You requested user with ID: john

The value is captured as a string, regardless of what was provided in the URL.

Using Multiple Route Parameters

You can define multiple parameters within a single route:

javascript
app.get('/users/:userId/posts/:postId', (req, res) => {
const { userId, postId } = req.params;
res.send(`Fetching post ${postId} by user ${userId}`);
});

When a request is made to /users/42/posts/123, the output would be:

Fetching post 123 by user 42

Optional Route Parameters

Express doesn't have built-in support for optional parameters, but you can achieve this using regular expressions:

javascript
app.get('/products/:category?', (req, res) => {
const category = req.params.category || 'all products';
res.send(`Viewing ${category}`);
});

With this route:

  • /products/electronics would show "Viewing electronics"
  • /products/ would show "Viewing all products"

Parameter Validation with Regular Expressions

You can restrict the format of parameters using regular expressions:

javascript
app.get('/users/:userId(\\d+)', (req, res) => {
res.send(`User ID: ${req.params.userId}`);
});

This route will only match if :userId consists of one or more digits. For example:

  • /users/42 will match
  • /users/john will not match

Note the double backslash \\d+ is needed because it's a string literal in JavaScript.

Practical Example: Building an API

Let's create a simple API for managing a list of books:

javascript
const express = require('express');
const app = express();
const port = 3000;

// Sample book data
const books = [
{ id: 1, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
{ id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' },
{ id: 3, title: '1984', author: 'George Orwell' }
];

// Get all books
app.get('/api/books', (req, res) => {
res.json(books);
});

// Get a specific book by ID
app.get('/api/books/:id', (req, res) => {
const id = parseInt(req.params.id);
const book = books.find(b => b.id === id);

if (!book) {
return res.status(404).json({ error: 'Book not found' });
}

res.json(book);
});

// Get books by author (demonstrating more complex parameters)
app.get('/api/authors/:author/books', (req, res) => {
const authorName = req.params.author;
const authorBooks = books.filter(book =>
book.author.toLowerCase().includes(authorName.toLowerCase())
);

res.json(authorBooks);
});

app.listen(port, () => {
console.log(`API server running at http://localhost:${port}`);
});

With this API:

  • /api/books would return all books
  • /api/books/2 would return "To Kill a Mockingbird"
  • /api/authors/Fitzgerald/books would return "The Great Gatsby"

Real-World Use Cases for Route Parameters

  1. User profiles: /users/:username to display a specific user's profile
  2. Product pages: /products/:productId to show details for a specific product
  3. Blog posts: /blog/:year/:month/:slug to organize blog content
  4. API versions: /api/:version/users to handle different API versions
  5. Language localization: /:language/documentation to serve content in different languages

Common Pitfalls and Best Practices

Parameter Type Conversion

Remember that all route parameters are captured as strings. If you need a different type (like numbers), you'll need to convert them:

javascript
app.get('/products/:id', (req, res) => {
const productId = parseInt(req.params.id, 10);

// Now productId is a number (if the parameter was a valid number)
if (isNaN(productId)) {
return res.status(400).send('Invalid product ID');
}

res.send(`Looking up product: ${productId}`);
});

Route Order Matters

Express matches routes in the order they're defined. Put more specific routes before more general ones:

javascript
// This specific route should come first
app.get('/users/profile', (req, res) => {
res.send('User profile page');
});

// This more general route with a parameter should come after
app.get('/users/:userId', (req, res) => {
res.send(`User ID: ${req.params.userId}`);
});

If you reversed this order, /users/profile would never be matched because Express would interpret "profile" as a :userId parameter.

Summary

Route parameters in Express provide a powerful way to build dynamic web applications with clean, readable URLs. They allow you to:

  • Create flexible routes that can handle variable parts
  • Access these variables easily through req.params
  • Build RESTful APIs and dynamic web applications
  • Apply validation to ensure parameters match expected formats

By mastering route parameters, you've taken an important step toward building more sophisticated Express applications that can respond dynamically to different user inputs and requests.

Further Exercises

  1. Build a simple blog API with routes for viewing posts by category, author, and date
  2. Create a route that accepts multiple optional parameters using regex patterns
  3. Implement parameter validation for a route that should only accept valid MongoDB ObjectId strings
  4. Design a RESTful API for a library system that uses route parameters to access books, authors, and genres

Additional Resources

Happy coding!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)