DEV Community

wahid
wahid

Posted on

4 1

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...

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (1)

Collapse
 
dotenv profile image
Dotenv •

💛🌴 ".env"

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more