Advanced Routing

Express supports advanced routing patterns, including string patterns, regular expressions, and modular route handlers.

1. String Patterns

Routes can match specific patterns using special characters like ?, +, *, and ().

// Matches "acd" and "abcd"
app.get('/ab?cd', (req, res) => res.send('ab?cd'));

// Matches "abcd", "abbcd", "abbbcd", etc.
app.get('/ab+cd', (req, res) => res.send('ab+cd'));

// Matches anything that starts with "ab" and ends with "cd"
app.get('/ab*cd', (req, res) => res.send('ab*cd'));

2. Regular Expression Routes

For more complex matching, you can use raw JavaScript Regular Expressions.

// Matches anything that has an "a" in it
app.get(/a/, (req, res) => res.send('/a/'));

// Matches any route ending with "fly" (butterfly, dragonfly)
app.get(/.*fly$/, (req, res) => res.send('/.*fly$/'));

3. Modular Routers

Use express.Router to create pluggable, modular route handlers. This is the standard way to organize large applications.

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

router.get('/', (req, res) => res.send('Birds home page'));
router.get('/about', (req, res) => res.send('About birds'));

module.exports = router;

// app.js
const birds = require('./routes/birds');
app.use('/birds', birds);
Tip: Keep your app.js clean by moving all route logic into the/routes directory.