Create Custom Middleware for Authentication in Express

Share this video with your friends

Social Share Links

Send Tweet

Express provides a straightforward workflow to add functionality between the request and the response.

In this space your application can check the request, query other APIs and build up the response in parts before sending the final response.

In this lesson, we'll add an authenication middleware that will check for a specific header and confirm that it has the correct value. If either of these tests fail then the middleware will send an early response with a 401 status.

Kevin Cunningham: [0:00] I'm going to create some custom middleware for my Express application. We're already using cors and express.json in our application. I'm going to create an authentication layer. utils/auth.js is where I'm going to create it. I'm going to create a function.

[0:17] Every middleware function Express takes three parameters, req, res, and next. Middleware will check something on the request or add something to the response and then when it's finished, it will call next.

[0:32] I'm going to check whether or not there's an x-api-key header. First of all, I'll check if the header doesn't exist, I'm going to send an early response back. Equally, if the header does exist but it's incorrect, I'm going to send an early response back.

[0:49] If(! Req.header("x-api-key")). Header is a helper function that Express adds to request to check the headers. If that header doesn't exist, or if the header does exist, but it's not equal to our test API key...Normally, for security, these should be environment variables that we would use .n for something to similar to store, rather than the code like this.

[1:16] In this instance, I'm just hard coding it. If either of those cases are true, then I'm going to set the status of the response to 401, which means unauthorized. Then I'll return a JSON object which will just say that the key was invalid.

[1:33] Otherwise, if everything was fine there, I'll call the next function, which just tells Express to keep going through the [inaudible] middleware and do the next one. I'll export this function, module.export = { auth }, and then I'll import it into my server file.

[1:47] Const { auth } = require("./utils.auth"). Now, I need to think about where am I going to use my authentication middleware? I don't want it on these images. I want that just to be a normal get that can be managed by others.

[2:03] I do want it here, so I just [inaudible] it there, and I do want all my quess as well. Now, I can [inaudible] as many middlewares as I want here until the response handler sends a response. Now, it's time to test that.

[2:19] If I test it now, you see I get an Invalid API key. That's the example when there is no x-api-key header. Let's add an x-api-key header and call it test, which is also incorrect. Great, that fails as well. Our real key is test-api-key. We test that, it comes back as we expect.