From the course: Mastering Nest.js: Build Scalable Applications with Mastery in Nest.js Framework

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Route-specific middleware

Route-specific middleware

Generally, when we apply a middleware in NestJS, it is applied globally for all routes. But what if we want to apply middleware only to specific routes? To understand that, let's take a look at an example. I have created a token middleware and I have given the use method. Now first of all, above the use method, I'm going to create a private read-only array and naming it as valid tokens, which will be of type string array. I'll define a few tokens in the array, random token 1, 2, and 3. Now inside the use method, I'm going to create a token constant. We are going to pass the token inside the headers. So we need to retrieve that token from the HTTP request headers. In token based authentication, the token is typically passed in the request headers, specifically in the authorization header. So let me assign request dot headers dot authorization. Now to check if the token is correct, I'll create a private method isValidToken, which will take a single argument token of type string and the…

Contents