DEV Community

wahid
wahid

Posted on

Adding API Key Middleware in NestJS

API Key Middleware is a secure way to protect your API by requiring users to include a valid API key in every request. In this guide, we'll walk through the steps to add API Key middleware to your NestJS application.

Step 1: Install NestJS

Before you begin, make sure you have Node.js and NestJS installed on your computer. If not, you can install NestJS with the following command:

npm install -g @nestjs/cli
nest new my-api
cd my-api
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Environment

Set up environment variables to store your API key. You can use nestjs/config to manage configuration. Create a .env file in your project directory and add the API key:

API_KEY=your-api-key
Enter fullscreen mode Exit fullscreen mode

Next, ensure you have set up the ConfigModule correctly in your AppModule:

import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";

@Module({
  imports: [ConfigModule.forRoot()],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Step 3: Create Middleware

Create an API Key middleware named ApiKeyMiddleware. Create a file named api-key.middleware.ts in the appropriate directory in your project and add the following code:
more...

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

💛🌴 ".env"