Express middleware
Learn how to create your own middleware for Express servers
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
Download the starter files and
cd
inRun
npm install
to install all the dependenciesRun
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
:
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.
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
Create a new middleware that runs before every request.
It should read the
sid
cookie and find the session info in thesessions
objectThen create a "session" property on the request object containing that info
Finally call the
next
function to tell Express to move on to the next handler.Change each handler that currently gets the session cookie to instead grab the info from
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
Amend the
GET /profile
handler to check whether there is a session.If not send a
401
HTML response with an error message in theh1
and a link to the/log-in
page.
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
Create a new middleware function named
checkAuth
that takesreq
,res
andnext
as arguments.If there is no
req.session
respond with the401
HTML.If there is a
req.session
callnext
to move on to the next handler.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.
Last updated