Adding Middleware in a Node.js API - Practical Examples

Explore practical examples of adding middleware in a Node.js API, enhancing functionality and security.
By Taylor

Adding Middleware in a Node.js API

Middleware in a Node.js API serves as a bridge between the request and response cycle. It allows you to add functionality like logging, authentication, and error handling, making your API more robust and easier to manage. Below are three diverse and practical examples of adding middleware in a Node.js API.

Example 1: Logging Middleware

Context

Logging middleware is useful for tracking requests made to your API. It can help you debug issues and monitor API usage. This middleware will log the HTTP method and URL of each request.

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

// Logging Middleware
app.use((req, res, next) => {
    console.log(`Received ${req.method} request for '${req.url}'`);
    next(); // Pass control to the next middleware or route
});

app.get('/api/data', (req, res) => {
    res.json({ message: 'Here is your data!' });
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Notes

  • You can improve this middleware by adding timestamps or IP addresses.
  • Consider using a logging library like winston or morgan for more advanced logging capabilities.

Example 2: Authentication Middleware

Context

Authentication middleware is crucial for securing your API. In this example, we’ll create a simple middleware that checks for a token in the request headers. If the token is missing or invalid, the request will be denied.

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

// Authentication Middleware
const authenticate = (req, res, next) => {
    const token = req.headers['authorization'];
    if (token && token === 'Bearer valid-token') {
        next(); // Token is valid, proceed with the request
    } else {
        res.status(401).json({ message: 'Unauthorized' }); // Deny access
    }
};

app.use(authenticate);

app.get('/api/protected', (req, res) => {
    res.json({ message: 'This is protected data!' });
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Notes

  • Use a secure method for token generation and validation in a real application.
  • Consider using libraries like jsonwebtoken for handling JWT (JSON Web Tokens).

Example 3: Error Handling Middleware

Context

Error handling middleware is essential for gracefully managing errors that occur in your API. This example demonstrates how to create middleware that catches errors and sends a user-friendly response.

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

app.get('/api/error', (req, res, next) => {
    const error = new Error('Something went wrong!');
    next(error); // Pass the error to the error handling middleware
});

// Error Handling Middleware
app.use((err, req, res, next) => {
    console.error(err.stack); // Log the error stack
    res.status(500).json({ message: 'Internal Server Error' }); // Send a user-friendly message
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Notes

  • Always ensure that error handling middleware is defined after all other middleware and routes.
  • Customize the error responses based on the type of error for better client-side handling.

These examples of adding middleware in a Node.js API illustrate how to enhance your API’s functionality and maintainability. By incorporating logging, authentication, and error handling, you can build a more robust application that serves your users effectively.