Routing & Parameters
Overview
Routing is the process of mapping a user's requested URL (e.g., /users/42) to a specific JavaScript function. Express utilizes an incredibly fast routing engine that supports dynamic variables. There are two primary ways users send data in a URL: Path Parameters (e.g., /users/:id, embedded directly in the path for identifying resources) and Query Strings (e.g., /users?sort=asc, appended at the end for filtering/sorting).
Syntax
const express = require('express');
const app = express();
// --- 1. PATH PARAMETERS (req.params) ---
// The colon (:) tells Express that 'userId' is a dynamic variable!
app.get('/api/users/:userId', (req, res) => {
// If URL is '/api/users/99'
const id = req.params.userId; // '99'
res.json({ message: `Fetching user ${id}` });
});
// --- 2. QUERY STRINGS (req.query) ---
// Express automatically parses everything after the question mark (?)
app.get('/api/search', (req, res) => {
// If URL is '/api/search?term=laptop&page=2'
const searchTerm = req.query.term; // 'laptop'
const pageNum = req.query.page; // '2'
res.json({ searchingFor: searchTerm, page: pageNum });
});Common Pitfalls
- Route Collisions. If you define
app.get('/api/users/:id')first, and then defineapp.get('/api/users/settings')below it, the 'settings' route will NEVER fire! Express will catch the word 'settings', assume it is an ID, and route it to the first handler (settingreq.params.id = 'settings'). Always put static routes above dynamic routes. - Trusting parameter types. EVERYTHING that comes from the URL is fundamentally parsed as a String. If you write
if (req.params.id === 99), it will fail because'99' !== 99. You must explicitly cast parameters to Numbers (e.g.,parseInt(req.params.id)).
Interview Questions
Path Parameters (/users/:id) should be used to uniquely identify a specific resource in the database. Query Strings (?sort=asc&limit=10) should be used to provide optional instructions on how to format, filter, or paginate a collection of resources.
Real-World Example
Using express.Router() to modularize routes into separate files, keeping app.js clean.
// --- routes/users.js ---
const express = require('express');
const router = express.Router(); // Creates a mini-app!
router.get('/:id', (req, res) => res.send('User Route'));
module.exports = router;
// --- app.js ---
const userRouter = require('./routes/users');
// Mounts the entire router under a specific prefix!
app.use('/api/users', userRouter);Check Your Knowledge
Test your understanding of Routing & Parameters with these quick questions.