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
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
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 {}
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)
💛🌴 ".env"