Back to all posts

Dynamic Routing with Node.js and Express


Dynamic routing is a powerful feature in web development that allows application to handle variable path segments in URLs. In Express.js, the popular Node.js web framework, dynamic routing enables developers to build flexible API and web applications that can respond intelligently to different URL patterns.

What is Dynamic Routing

Dynamic routing allows your application to respond to URLs with variable parameters. Instead of creating separate route handlers for each possible URL path, you can define patterns that extract values from the URL itself.

Basic Implementation with Express

Setting up dynamic routes in Express is straightforward:

const express = require('express');
const app = express();

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

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

In this example :userId is a route parameter that caputes any value in that position of the URL.

Multiple Parameters

Express can handle multiple dynamic segments in a single route:

app.get('/products/:category/:productId', (req, res) => {
  const { category, productId } = req.params;
  res.send(`Category: ${category}, Product ID: ${productId}`);
});

Optional Parameters and Patterns

You can create more advanced routing patterns using regular expressions:

// Only match numeric IDs
app.get('/users/:userId(\\d+)', (req, res) => {
  // This will only match if userId consists of digits
  res.send(`User ID: ${req.params.userId}`);
});

// Optional parameters with ?
app.get('/posts/:year?/:month?', (req, res) => {
  const { year, month } = req.params;
  if (year && month) {
    res.send(`Posts from ${month}/${year}`);
  } else if (year) {
    res.send(`Posts from ${year}`);
  } else {
    res.send('All posts');
  }
});

Route Order Matters

Express evaluates routes in the order they’re defined. Always place more specific routes before more general ones:

// Specific route first
app.get('/users/profile', (req, res) => {
  res.send('User profile page');
});

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

Creating Modular Routing

For larger applications, Organize routes using Express Router:

// userRoutes.js
const express = require('express');
const router = express.Router();

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

router.get('/:userId/posts', (req, res) => {
  res.send(`Posts by user ${req.params.userId}`);
});

module.exports = router;

// app.js
const userRoutes = require('./userRoutes');
app.use('/users', userRoutes);

Dynamic routing in Express.js provides a flexible foundation for building modern web applications and APIs. By mastering these concepts, you can create cleaner, more maintainble code while offering powerful URL handling capabilities.