Creating Express middleware for routes
Middleware can be used for both generic Express route configurations and in very specific use cases. The general pattern of middleware transformations in Express is always consistent, so your main concern is the scope and order of when middleware should be used. Let's explore how to create custom Express middleware that we will use only on specific route contexts.
Getting ready
Let's create a new middleware layer that uses our application's session property to check whether a user is authorized to use a specific API. This middleware will be included on all the secured API routes of our application and will check whether the user session is an admin role, before allowing the request through. This sort of user role middleware is useful to protect sensitive parts of your application from unauthorized users.
How to do it...
Perform the following steps to create custom Express middleware for authentication:
- First, let's create a new middleware file called
/middleware...