Protecting Express Routes with Auth Middleware
Explore how to protect Express.js routes by implementing authentication middleware that verifies JWT tokens. Learn to extract tokens from authorization headers, handle token verification with jwt.verify, and attach authenticated user data to requests. Understand how this middleware guards routes against unauthorized access by returning appropriate 401 errors for missing, expired, or tampered tokens. This lesson helps you create reusable middleware to secure backend routes effectively before moving on to role-based access control.
The previous lesson issued tokens at login. This lesson shows how to use them. Before a protected route runs its logic, it must check that the request includes a valid token. Doing that check inside every controller would duplicate the same logic across handlers. Express middleware solves this by moving the check into the request pipeline: one protect function runs before the route handler, verifies the token, and either passes control to the route handler or rejects the request. This lesson builds that guard and applies it to protected routes.
Note: This is Express middleware and is read-along. It uses
jwt.verify()from the previous lesson and theUsermodel and reads the token a client sends in theAuthorizationheader.
To make the guard concrete, the next visual should show a request passing through the middleware before reaching the route:
That starts with where the token comes from: