Routing in Express.js

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

Routing in Express.js refers to defining endpoints (URLs) of your application and determining how the server responds to client requests.

Routes are essential for building REST APIs or web applications.


1. Basic Routing

const express = require('express'); const app = express(); const port = 3000; // Home route app.get('/', (req, res) => { res.send('Welcome to Express.js!'); }); // About route app.get('/about', (req, res) => { res.send('About Page'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

Explanation:

  • app.get(path, callback) – Handles GET requests to a specific path.

  • res.send() – Sends a response to the client.


2. Route Methods

Express supports all HTTP methods:

MethodUsage Example
GETapp.get('/users', ...)
POSTapp.post('/users', ...)
PUTapp.put('/users/:id', ...)
DELETEapp.delete('/users/:id', ...)
PATCHapp.patch('/users/:id', ...)

Example: CRUD operations for users

// Create user app.post('/users', (req, res) => { res.send('User created'); }); // Update user app.put('/users/:id', (req, res) => { res.send(`User ${req.params.id} updated`); }); // Delete user app.delete('/users/:id', (req, res) => { res.send(`User ${req.params.id} deleted`); });

3. Route Parameters

Route parameters allow you to capture values in the URL.

app.get('/users/:userId', (req, res) => { res.send(`User ID is ${req.params.userId}`); });
  • URL: /users/123 → Response: User ID is 123


4. Query Parameters

Query parameters are passed after ? in the URL.

app.get('/search', (req, res) => { const { q } = req.query; res.send(`You searched for: ${q}`); });
  • URL: /search?q=express → Response: You searched for: express


5. Chaining Route Handlers

You can chain multiple handlers for a single route:

app.get('/chain', (req, res, next) => { console.log('First handler'); next(); }, (req, res) => { res.send('Second handler executed'); } );

6. Router-Level Routing

Express allows you to create modular route handlers using express.Router().

const router = express.Router(); // Define routes router.get('/profile', (req, res) => res.send('User Profile')); router.get('/settings', (req, res) => res.send('User Settings')); // Use the router app.use('/user', router);
  • /user/profileUser Profile

  • /user/settingsUser Settings


7. Best Practices

  • Use Router for modular code.

  • Use consistent route naming (plural nouns for resources: /users, /posts).

  • Separate routes into different files for large projects.


Routing is the backbone of any Express.js application, and mastering it is crucial for building RESTful APIs and full-stack apps.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes