Express middleware

Learn how to create your own middleware for Express servers

  • js
  • express
  • middleware
Leave feedback

Learn how to write your own Express middleware to do logging and authentication.

Middleware

Express is built around middleware. Middleware are functions that receive a request, do something with it, then either pass the request on to the next middleware or send a response (ending the chain).

Technically all route handlers are middleware, since they fit the above definition. However middleware usually transform the request in some way and don’t actually send a response.

For example the built in express.urlencoded middleware grabs the HTTP request body, turns it into an object, then attaches it to the request object. This allows subsequent handlers to easily access it at request.body. The 3rd party cookie-parser middleware does the same for cookies. We’re going to learn how to create our own middleware functions.

Setup

  1. Download the starter files and cd in
  2. Run npm install to install all the dependencies
  3. Run npm run dev to start the development server

Visit http://localhost:3000 to see the workshop app. You can “log in” by entering an email, which will be saved as a cookie so the server can identify you.

Our first middleware

It would be useful if our server logged each incoming request to our terminal. That way we can see a log of what’s happening as we use our server locally.

Usually we match our handlers to specific routes (e.g. server.get("/about", ...). However we can run a handler for every route by using server.use:

server.use((req, res) => {
console.log(`${req.method} ${req.url}`);
});

This will log the method and URL for every request the server receives (e.g. GET / or POST /submit). Unfortunately that’s all it will do, as this handler never tells the next handler in the chain to run. This will cause all requests to time out, since the server never sends a response using response.send.

We can fix this with the third argument all handlers receive: next. This is a function you call inside a handler when you want Express to move on to the next one.

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

This tells Express to run the logger handler before every request, then move on to whatever handler is queued for that route. E.g. if the user requests the home page (GET /) this handler will run, log the method/URL, then pass on to the next handler that matches GET /, which will send an HTML response.


Authentication middleware

Note: we are just storing all the session info about the user in an object in-memory. In a real app you’d want this to live in a persistent store like a database.

Accessing the user

Currently we are accessing the user cookie in three handlers (GET /, GET /profile and GET /profile/settings). We have to grab the session ID from the signed cookies, then look the session info up in the sessions object. This ends up being quite a lot of code repeated whenever we want to find out info about which user is currently logged in. We can create a middleware to handle this repeated task.

We don’t know which routes will want to access the logged in user value so we’ll set this middleware on the whole app using server.use. We’ll mimic the other middleware we’re using and add the user value to the req object. This lets us pass values down through the request chain to later handlers.

Challenge 1.1

  1. Create a new middleware that runs before every request.
  2. It should read the sid cookie and find the session info in the sessions object
  3. Then create a “session” property on the request object containing that info
  4. Finally call the next function to tell Express to move on to the next handler.
  5. Change each handler that currently gets the session cookie to instead grab the info from req.session.
Toggle answer
server.use((req, res, next) => {
const sid = req.signedCookies.sid;
const sessionInfo = sessions[sid];
if (sessionInfo) {
req.session = sessionInfo;
}
next();
});

server.get("/", (req, res) => {
const user = req.session;
// ...
});

server.get("/profile", (req, res) => {
const user = req.session;
// ...
});

server.get("/profile/settings", (req, res) => {
const user = req.session;
// ...
});

Protecting routes

Currently our GET /profile route is broken. If the user isn’t logged in we get an error trying to access user.email (since req.session is undefined). It would be better to show a “Please log in” page for unauthenticated users.

Challenge 1.2

  1. Amend the GET /profile handler to check whether there is a session.
  2. If not send a 401 HTML response with an error message in the h1 and a link to the /log-in page.
Toggle answer
server.get("/profile", (req, res) => {
const user = req.session;
if (!user) {
res.status(401).send(`
<h1>Please log in to view this page</h1>
<a href="/log-in">Log in</a>
`
);
} else {
res.send(`<h1>Hello ${user.email}</h1>`);
}
});

Now you should see the “please log in” page if you visit /profile when you aren’t logged in. However the GET /profile/settings route has the same problem.

We could copy paste the above code, but it would be better to avoid the duplication and move this logic into a middleware that makes sure users are logged in.

Challenge 1.3

  1. Create a new middleware function named checkAuth that takes req, res and next as arguments.
  2. If there is no req.session respond with the 401 HTML.
  3. If there is a req.session call next to move on to the next handler.
  4. Add this middleware in front of the handler for any route we want to protect. We don’t want this middleware running on all routes, since some of them are public.

Hint: you can set multiple middleware/handlers for a route by passing multiple arguments.

server.get("/example", doSomething, anotherHandler, (req, res) => {
// ...
});
Toggle answer
function checkAuth(req, res, next) {
const user = req.session;
if (!user) {
res.status(401).send(`
<h1>Please log in to view this page</h1>
<a href="/log-in">Log in</a>
`
);
} else {
next();
}
}

server.get("/profile", checkAuth, (req, res) => {
// ...
});

server.get("/profile/settings", checkAuth, (req, res) => {
// ...
});