MCPcopy Index your code
hub / github.com/Lokicoule/nestjs-cognito

github.com/Lokicoule/nestjs-cognito @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
447 symbols 880 edges 213 files 45 documented · 10% updated 13d ago@nestjs-cognito/auth@2.5.1 · 2025-11-13★ 1101 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

NestJS-Cognito

Coverage Status License: MIT GitHub Stars

AWS Cognito authentication for NestJS

Stop writing boilerplate. Protect your routes with a decorator.


What is this?

You're building a NestJS app. You chose AWS Cognito for authentication. Now you need to verify JWT tokens, handle multiple user pools, extract tokens from headers or cookies, and implement role-based authorization.

You could spend days writing boilerplate. Or you could use this.

One decorator protects your routes. Built on aws-jwt-verify.

@Controller('profile')
@Authentication()  // That's it. Route protected.
export class ProfileController {
  @Get()
  getProfile(@CognitoUser() user: CognitoJwtPayload) {
    return { username: user['cognito:username'] };
  }
}

Why use this?

  • Fast setup — 5 minutes from install to protected routes
  • Type-safe — Full TypeScript support
  • Production-ready — Built on AWS's official JWT verification library
  • Zero boilerplate — Decorators replace hundreds of lines
  • Flexible — REST, GraphQL, cookies, multiple user pools, custom extractors
  • Testable — Mock and E2E test utilities included

Quick start

Install:

npm install @nestjs-cognito/core @nestjs-cognito/auth

Configure:

import { CognitoAuthModule } from '@nestjs-cognito/auth';

@Module({
  imports: [
    CognitoAuthModule.register({
      jwtVerifier: {
        userPoolId: 'us-east-1_xxxxx',
        clientId: 'your-client-id',
        tokenUse: 'access',
      },
    }),
  ],
})
export class AppModule {}

Protect routes:

import { Authentication, Authorization, CognitoUser } from '@nestjs-cognito/auth';

@Controller('admin')
@Authorization(['admin'])
export class AdminController {
  @Get('dashboard')
  getDashboard(@CognitoUser() user: CognitoJwtPayload) {
    return { message: `Welcome ${user['cognito:username']}` };
  }
}

Done.

Packages

Package What it does npm
@nestjs-cognito/core JWT verification, token extraction npm
@nestjs-cognito/auth Decorators, guards, authorization npm
@nestjs-cognito/graphql GraphQL authentication npm
@nestjs-cognito/testing Mock and E2E test utilities npm

Examples

Role-based authorization

@Controller('content')
export class ContentController {
  @Get()
  @Authorization({ allowedGroups: ['user', 'admin'] })
  list() {
    return { content: [] };  // Either user OR admin can access
  }

  @Post()
  @Authorization({ requiredGroups: ['moderator', 'admin'] })
  create() {
    return { created: true };  // Must be BOTH moderator AND admin
  }

  @Delete(':id')
  @Authorization({
    allowedGroups: ['admin'],
    prohibitedGroups: ['banned']  // Admins yes, banned users no
  })
  delete() {
    return { deleted: true };
  }
}

Public routes with optional auth

@Controller('products')
@Authentication()
export class ProductsController {
  @Get(':id')
  @PublicRoute()
  getProduct(@Param('id') id: string, @CognitoUser() user?: CognitoJwtPayload) {
    const product = this.findProduct(id);

    return {
      ...product,
      price: user ? this.getMemberPrice(product) : product.regularPrice,
      memberBenefits: user ? this.getBenefits(product) : null,
    };
  }
}

GraphQL

import { GqlAuthentication, GqlAuthorization, GqlCognitoUser } from '@nestjs-cognito/graphql';

@Resolver()
@GqlAuthentication()
export class UserResolver {
  @Query(() => User)
  me(@GqlCognitoUser() user: CognitoJwtPayload) {
    return {
      id: user.sub,
      username: user['cognito:username'],
      email: user.email,
    };
  }

  @Query(() => [User])
  @GqlAuthorization(['admin'])
  users() {
    return this.userService.findAll();
  }
}

Multiple user pools

CognitoAuthModule.register({
  jwtVerifier: [
    {
      userPoolId: 'us-east-1_customers',
      clientId: 'customer-app-client',
      tokenUse: 'access',
    },
    {
      userPoolId: 'us-east-1_employees',
      clientId: 'admin-app-client',
      tokenUse: 'id',
    },
  ],
})

Cookie authentication

import { CookieJwtExtractor } from '@nestjs-cognito/core';

CognitoAuthModule.register({
  jwtExtractor: new CookieJwtExtractor('access_token'),
  jwtVerifier: {
    userPoolId: 'us-east-1_xxxxx',
    clientId: 'your-client-id',
    tokenUse: 'id',
  },
})

Testing

import { CognitoTestingModule } from '@nestjs-cognito/testing';

const module = await Test.createTestingModule({
  imports: [
    CognitoTestingModule.register({}, {
      enabled: true,
      user: {
        username: 'test-user',
        email: 'test@example.com',
        groups: ['users'],
      },
    }),
    AppModule,
  ],
})
  .overrideProvider(COGNITO_JWT_VERIFIER_INSTANCE_TOKEN)
  .useFactory({ factory: CognitoTestingModule.createJwtVerifierFactory })
  .compile();

Contributing

Found a bug? Have an idea? Pull requests are welcome.

  1. Fork the repo
  2. Create your feature branch
  3. Commit your changes
  4. Push and open a PR

See CONTRIBUTING.md for details.

Documentation

Full documentation →

Package READMEs: - Core - Auth - GraphQL - Testing - Examples

License

MIT


Made by @Lokicoule

Extension points exported contracts — how you extend this code

Core symbols most depended-on inside this repo

Shape

Function 163
Class 158
Method 115
Interface 11

Languages

TypeScript100%

Modules by API surface

apps/docs/src/components/Search.tsx20 symbols
apps/docs/src/components/Code.tsx13 symbols
packages/auth/lib/user/user.builder.ts11 symbols
apps/docs/src/components/mdx.tsx11 symbols
packages/auth/lib/user/user.model.ts10 symbols
packages/testing/lib/cognito-testing.service.ts9 symbols
packages/auth/lib/abstract.guard.spec.ts9 symbols
packages/testing/lib/cognito-mock.service.ts8 symbols
packages/core/lib/adapters/cognito-jwt-verifier.adapter.ts8 symbols
apps/docs/src/components/Navigation.tsx8 symbols
packages/auth/lib/validators/abstract.validator.ts7 symbols
apps/docs/src/components/SectionProvider.tsx7 symbols

For agents

$ claude mcp add nestjs-cognito \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page