URL Params & Query

Handling dynamic data in URLs is a core requirement for any web application. Express makes it easy to access these values.

1. Route Parameters (req.params)

Parameters are named segments of the URL that are captured and stored in req.params. They are defined in the route path with a colon.

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

2. Multi-Parameter Routes

// Path: /flights/:from-:to
// URL: /flights/LAX-SFO
app.get('/flights/:from-:to', (req, res) => {
  res.json(req.params); // { from: 'LAX', to: 'SFO' }
});

3. Query Strings (req.query)

Query strings are the part of a URL after the ?. They don't need to be defined in the route.

// URL: /search?term=node&filter=recent
app.get('/search', (req, res) => {
  const { term, filter } = req.query;
  res.send(`Searching for ${term} with ${filter} filter`);
});
Key Difference: Use Params for resources (e.g., getting a specific user) and Query for optional modifiers (e.g., searching, sorting, or pagination).