Search code examples
node.jsexpresserror-handlingmiddleware

Does the position of error handling middleware matter in express?


I was just curious since I thought it wouldn't matter where you place the middleware in your code as long as it's in the app/index.js

What I mean is this:

const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");

const app = express();
dotenv.config();

// MIDDLEWARE
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(cors());

// ROUTES
const { errorHandler } = require("./middleware/errorMiddleware");
const goalRoutes = require("./routes/goalRoutes");

app.use("/api/goals", goalRoutes);

app.use(errorHandler);

If I put the errorHandler middleware above the routes like this:

// MIDDLEWARE
const { errorHandler } = require("./middleware/errorMiddleware");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));


app.use(cors());
app.use(errorHandler);

// ROUTES

const goalRoutes = require("./routes/goalRoutes");
app.use("/api/goals", goalRoutes);

The errorHandler wouldn't work anymore. Does the position matter for this kind of middleware? What other types of middleware needs to be in a proper position?


Solution

  • Yes, position of middleware functions in express needs to be proper.

    Middleware functions in express work between a client's request and response. Every middleware function has access to request, response and its following middleware function. Middleware functions are executed in the order specified and skip error handling functions until it is invoked.

    app.use(middleware1);
    app.use(middleware2);
    app.use(middleware3);
    

    In the above example, middleware1 will be executed first and it invokes middleware2 by using,

    next();
    
    • Say middleware2 is an error handler method with a next function. middleware3 will not be executed unless an error occurred. Because error handling methods are executed only when it is invoked.
    • Say middleware2 is an error handler method without a next function. middleware3 will not be executed at all.

    so, error handling function must be at the middleware stack's last (also at the last of route handling methods).