Routing in Express.js

📘 Node.js 👁 55 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Routing in Express.js determines how an application responds to client requests based on the URL path and HTTP method.

In simple terms, routing connects:
Request → Logic → Response


1. What Is a Route?

A route consists of:

  • HTTP method (GET, POST, PUT, DELETE)

  • URL path

  • Handler function

app.get('/home', (req, res) => { res.send('Home Page'); });

2. Basic Routing Methods

Express provides methods matching HTTP verbs:

app.get() // Read data app.post() // Create data app.put() // Update data app.delete() // Delete data

3. Route Parameters

Used to capture dynamic values from URLs.

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

✔ Useful for user profiles, product IDs


4. Query Parameters

Passed after ? in the URL.

app.get('/search', (req, res) => { res.send(req.query); });

Example:

/search?term=node&limit=10

5. Multiple Route Handlers

More than one handler can be used for a route.

app.get('/data', (req, res, next) => { console.log('Step 1'); next(); }, (req, res) => { res.send('Final Response'); } );

6. Route Grouping with express.Router()

Used to organize routes into separate files.

users.js

const express = require('express'); const router = express.Router(); router.get('/', (req, res) => { res.send('All users'); }); router.get('/:id', (req, res) => { res.send(`User ${req.params.id}`); }); module.exports = router;

app.js

app.use('/users', require('./users'));

7. Route Matching Order

  • Routes are matched top to bottom

  • First matching route is executed

⚠ Order matters!


8. Handling All HTTP Methods

app.all('/info', (req, res) => { res.send('Handles all requests'); });

9. Route Patterns

app.get('/ab?cd', handler); // acd or abcd app.get('/ab+cd', handler); // abcd, abbcd app.get('/ab*cd', handler); // abANYcd

10. Error Handling in Routes

app.get('/error', (req, res, next) => { next(new Error('Something broke')); });

11. Best Practices

  • Keep routes clean and simple

  • Use routers for modular structure

  • Validate route parameters

  • Follow RESTful conventions


12. Summary

  • Routing defines how requests are handled

  • Express routes depend on HTTP method and URL

  • express.Router() improves code structure

  • Route order is important


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes