typescript 42 lines · 8 steps

Building an API-key auth strategy in NestJS

A Passport strategy that authenticates requests by their X-Api-Key header and resolves the calling consumer.

Explained by highlit
1import { Injectable, UnauthorizedException } from '@nestjs/common';
2import { PassportStrategy } from '@nestjs/passport';
3import { Strategy } from 'passport-headerapikey';
4import { ConfigService } from '@nestjs/config';
5import { ApiKeyService } from './api-key.service';
6import { ApiConsumer } from './api-consumer.entity';
7 
8@Injectable()
9export class ApiKeyStrategy extends PassportStrategy(Strategy, 'api-key') {
10 constructor(
11 private readonly apiKeyService: ApiKeyService,
12 config: ConfigService,
13 ) {
14 super(
15 { header: 'X-Api-Key', prefix: '' },
16 true,
17 async (apiKey: string, done: (err: Error | null, consumer?: ApiConsumer | false) => void) => {
18 try {
19 const consumer = await this.validate(apiKey);
20 done(null, consumer);
21 } catch (err) {
22 done(err as Error);
23 }
24 },
25 );
26 }
27 
28 private async validate(apiKey: string): Promise<ApiConsumer> {
29 const consumer = await this.apiKeyService.resolveByKey(apiKey);
30 
31 if (!consumer || consumer.revokedAt) {
32 throw new UnauthorizedException('Invalid or revoked API key');
33 }
34 
35 if (consumer.expiresAt && consumer.expiresAt.getTime() < Date.now()) {
36 throw new UnauthorizedException('API key has expired');
37 }
38 
39 await this.apiKeyService.touchLastUsed(consumer.id);
40 return consumer;
41 }
42}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1PassportStrategy lets you wrap any Passport strategy into an injectable NestJS provider with a named key.
  2. 2The verify callback bridges Passport's node-style callbacks to async validation by translating resolved values and thrown errors.
  3. 3Centralizing key checks — existence, revocation, and expiry — in one method keeps authentication logic auditable and reusable.

Related explainers

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
python
import time
import uuid
 
from django.utils.deprecation import MiddlewareMixin

Attaching per-request context in Django

middleware request lifecycle multi-tenancy
Intermediate 7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps

Share this explainer

Here's the card — post it anywhere.

Building an API-key auth strategy in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code