WikiGalaxy

Personalize

Handling Routes and Middleware in Express.js

Understanding Express.js Routing

Routing in Express.js refers to how an application’s endpoints (URIs) respond to client requests. It determines the response that should be sent back to a client based on the HTTP request method and the URL.

Middleware in Express.js

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware can perform tasks like executing code, modifying request and response objects, ending the request-response cycle, and calling the next middleware function.

Benefits of Using Middleware

Middleware enhances modularity and reusability by allowing developers to separate concerns and manage requests more effectively. This separation leads to cleaner and more maintainable code.

Common Use Cases for Middleware

Middleware is commonly used for logging, authentication, error handling, and data parsing in Express.js applications.

Types of Middleware

There are several types of middleware in Express.js, including application-level middleware, router-level middleware, error-handling middleware, built-in middleware, and third-party middleware.

Basic Routing

Defining Routes

In Express.js, defining routes involves specifying the HTTP method and the path. The callback function defines the response sent back to the client.


const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
        

Explanation

This example demonstrates a basic route in Express.js. The app listens for GET requests at the root URL ('/') and responds with 'Hello World!'.

Route Parameters

Using Route Parameters

Route parameters are used to capture values specified at their position in the URL. They are named segments prefixed by a colon (:) in the route path.


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

Explanation

This route captures a user ID from the URL and responds with it. If a request is made to '/users/123', the response will be 'User ID is: 123'.

Middleware Functions

Creating Middleware

Middleware functions can be created and applied to routes to execute specific tasks before sending a response.


const logRequest = (req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
};

app.use(logRequest);

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

Explanation

Here, a middleware function 'logRequest' logs the HTTP method and URL of each request. The 'next()' function passes control to the next middleware or route handler.

Error Handling Middleware

Implementing Error Handling

Error-handling middleware is defined similarly to other middleware but with four arguments: err, req, res, and next.


app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});
        

Explanation

This middleware catches errors in the application and sends a 500 status code along with a message. It's essential for handling unexpected issues gracefully.

Third-party Middleware

Integrating Third-party Middleware

Express.js allows the integration of third-party middleware to extend its functionality. Common examples include 'body-parser' for parsing request bodies and 'cors' for enabling Cross-Origin Resource Sharing.


const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.post('/data', (req, res) => {
    res.send(req.body);
});
        

Explanation

In this example, 'body-parser' middleware is used to parse JSON bodies of incoming requests, making it easier to handle POST data.

Router-level Middleware

Using Router-level Middleware

Router-level middleware works similarly to application-level middleware but is bound to an instance of express.Router().


const router = express.Router();

router.use((req, res, next) => {
    console.log('Router-level middleware');
    next();
});

router.get('/about', (req, res) => {
    res.send('About Page');
});

app.use('/', router);
        

Explanation

This example shows how middleware can be applied to specific routes using express.Router(). It logs a message whenever the '/about' route is accessed.

Chaining Middleware

Chaining Multiple Middleware Functions

Express.js allows chaining multiple middleware functions to handle a request by passing control from one function to the next.


const checkAuth = (req, res, next) => {
    console.log('Checking authentication');
    next();
};

const logTime = (req, res, next) => {
    console.log('Time:', Date.now());
    next();
};

app.get('/dashboard', checkAuth, logTime, (req, res) => {
    res.send('Dashboard');
});
        

Explanation

In this example, two middleware functions are chained for the '/dashboard' route. 'checkAuth' checks authentication, and 'logTime' logs the current time before sending the response.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025