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

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

💛🌴 ".env"

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay