Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sun Apr 02 2023

Middlewares in express

What is middlewares in express? The answer is fairly simple - it is functions that will be executed when an endpoint gets a request. They will be executed in the order that they are inserted into the use() function. We can specify what routes that should have specific middlewares, for example - imagine we have an API where we expect an access token to be present in the request, then we might create a middleware for checking this. But we also might have some endpoints that should be open for all consumers, like a /docs endpoint, then we can make our middleware only be executed for certain routes.

Middlewares specs

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

Read more at the express docs

In this guide, we will set up a server with some endpoints, some that will trigger some specific middlewares, and some that will be without them. We will also write our own middlewares. Hope you enjoy it!

Quick set up

mdkir middleware-example cd middleware-example npm init npm install express touch index.js

Creating our server

Let's write some code in our index.js:

const express = require("express"); const { secretRouter } = require("./secretRoutes"); const app = express(); const PORT = 3500; app.use("/api", secretRouter); app.get("/docs", (req, res) => { res.send({ docs: "This endpoint is open for anyone" }); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });

We have here, two endpoints. One that should be protected, and one that is open for anyone. We will have a router called secretRouter for all the secret routes.

Creating secretRoutes.js

Now we will create our secret routes router. We will have two example endpoints. As seen, we are sending req.secretKey in the response. That is a value we need to set in our middlewares. We are also checking that there is a secret token in the request headers.

The order of the middlewares are

  • verifyToken
  • addSecret

So before the request is reaching addSecret, it must pass verifyToken.

const express = require("express"); const { verifyToken, addSecret } = require("./middlewares"); const secretRouter = express.Router({ mergeParams: true }); secretRouter.use(verifyToken); secretRouter.use(addSecret); secretRouter.get("/user/:id", (req, res) => { res.send({ user: { name: "Secret user", key: req.secretKey } }); }); secretRouter.get("/user/:id/confidential", (req, res) => { res.send({ data: "This data is confidential", key: req.secretKey }); }); module.exports = { secretRouter };

Create middlewares

Let's write our middlewares.js file:

const verifyToken = (req, res, next) => { const token = req.headers["secret_key"]; if (!token) { res.send("You are not welcome here"); } else if (token !== "SECRET_VALUE") { res.send("Wrong value of token"); } // Next will call next middleware in line next(); }; const addSecret = (req, res, next) => { req.secretKey = "super secret key"; // Next will call next middleware in line next(); }; module.exports = { verifyToken, addSecret };

Try it out

When testing the endpoints, you can use Postman and add our header like image below is showing.

Image of postman

Testing /docs endpoint

Request

GET localhost:3500/docs

Response

{ "docs": "This endpoint is open for anyone" }

Testing /user/:id endpoint

GET localhost:3500/api/user/123

Without header

You are not welcome here

Without wrong header value

Wrong value of token

With correct header set

{ "user": { "name": "Secret user", "key": "super secret key" } }

Testing /user/:id/confidential endpoint

GET localhost:3500/api/user/123/confidential

Response with correct header value

{ "data": "This data is confidential", "key": "super secret key" }

Outro

In this short guide we took a look at how we can create our own middlewares in an express application. Middlewares are really handy when we want to do some checks before our endpoints get reached, or if we want to add or manipulate the request object in any way before the request reaches our logical part of it. Instead of checking the validity of each request in our controllers for example, we do it in one place before the controller is even reached.

If you have worked with express before, you have probably used a lot of third-party middlewares, maybe without even knowing about it. Some examples of known third.party middlewares:

app.use(bodyParser()); app.use(cors()); app.use(cookieParser());

Read more about cors here

I hope you enjoyed this post. If you have any feedback, just hit me up with an email. You find it here.

Have a good day!

signatureSun Apr 02 2023
See all our articles