Blog>
Snippets

Dynamic Route Segments with Typed Parameters

Implement dynamic route segments with typed parameters such as integers or slugs, enhancing route pattern matching and parsing.
// Define a route using Express to parse an integer parameter
const express = require('express');
const app = express();

app.get('/items/:id(\d+)', (req, res) => {
  // The route will only match if :id is an integer
  const itemId = parseInt(req.params.id, 10);
  res.send(`Item ID is an integer: ${itemId}`);
});

app.listen(3000, () => console.log('Server started on port 3000'));
This code snippet uses Express.js to create a server that defines a route with a dynamic segment that expects an integer as a parameter. The `(\d+)` part of the route ensures that the `id` parameter can only be an integer. The `parseInt` function then parses the parameter to an integer.
// Define a route using Express to parse a slug parameter
const express = require('express');
const app = express();

app.get('/posts/:title([a-z0-9-]+)', (req, res) => {
  // The route will only match if :title is a slug (lowercase letters, numbers, and dashes)
  const postTitleSlug = req.params.title;
  res.send(`Post title slug is: ${postTitleSlug}`);
});

app.listen(3000, () => console.log('Server started on port 3000'));
This code snippet uses Express.js to create a server that defines a route with a dynamic segment that expects a slug as a parameter. A slug typically contains lowercase letters, numbers, and hyphens. The `([a-z0-9-]+)` part of the route pattern ensures that the `title` parameter matches the slug pattern.