Quick Start
Let's get Cognito authentication working in your NestJS app. This should take about 5 minutes.
Installation
pnpm add @nestjs-cognito/auth
Setup
Step 1: Add your Cognito credentials
Create a .env file with your User Pool ID and Client ID:
COGNITO_USER_POOL_ID=your-user-pool-id
COGNITO_CLIENT_ID=your-client-id
Step 2: Configure the module
Add CognitoAuthModule to your app module:
import { Module } from '@nestjs/common';
import { CognitoAuthModule } from '@nestjs-cognito/auth';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot(),
CognitoAuthModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
jwtVerifier: {
userPoolId: configService.get('COGNITO_USER_POOL_ID'),
clientId: configService.get('COGNITO_CLIENT_ID'),
tokenUse: 'access',
},
}),
}),
],
})
export class AppModule {}
Usage
Protect a route
Add @Authentication() to any route that needs authentication:
import { Controller, Get } from '@nestjs/common';
import { Authentication, CognitoUser } from '@nestjs-cognito/auth';
import type { CognitoJwtPayload } from "@nestjs-cognito/core";
@Authentication()
@Controller('users')
export class UsersController {
@Get('profile')
getProfile(@CognitoUser() user: CognitoJwtPayload) {
return user;
}
}
Allow public access
Use @PublicRoute() on routes that should be accessible without authentication:
import { Controller, Get } from '@nestjs/common';
import { Authentication, PublicRoute } from '@nestjs-cognito/auth';
@Authentication()
@Controller('auth')
export class AuthController {
@PublicRoute()
@Get('health')
health() {
return { status: 'ok' };
}
}
Restrict by user group
Require users to belong to specific Cognito groups:
import { Controller, Get } from '@nestjs/common';
import { Authentication, Authorization } from '@nestjs-cognito/auth';
@Authorization(['admin'])
@Controller('admin')
export class AdminController {
@Get('dashboard')
adminDashboard() {
return { message: 'Admin dashboard' };
}
}