npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@hichchi/nest-auth

v0.0.9

Published

NestJS authentication extension library that extends @hichchi/nest-core functionality with comprehensive JWT tokens, Google OAuth, local authentication, role-based access control, permission guards, user caching, encryption services, token management, and

Readme

🔐 @hichchi/nest-auth

Description

NestJS authentication extension library that extends @hichchi/nest-core functionality with comprehensive JWT tokens, Google OAuth, local authentication, role-based access control, permission guards, user caching, encryption services, token management, and enterprise-grade security features - cannot be used independently, requires nest-core as foundation

npm version npm downloads License: MIT NestJS

Part of the Hichchi ecosystem - A powerful, scalable application built with Nx workspace

📚 Jump to Documentation


📋 Table of Contents


📦 Installation

npm install @hichchi/nest-core @hichchi/nest-auth

⚡ Quick Start

Get up and running with authentication in just a few minutes! This guide will walk you through setting up a complete authentication system with JWT tokens, user management, and secure endpoints.

1. Create a NestJS service implementing IUserService

First, you need to create a service that handles user operations in your database. This service must implement the IUserService interface to work with the authentication module.

NOTE: All available methods can be found in the IUserService interface documentation.

import { Injectable } from "@nestjs/common";
import { GoogleProfile, IUserService } from "@hichchi/nest-auth";
import { AuthProvider, User } from "@hichchi/nest-connector/auth";
import { EntityId } from "@hichchi/nest-connector/crud";

@Injectable()
export class UserService implements IUserService {
  /**
   * Find user by email address (required for email-based authentication)
   */
  getUserByEmail(email: string): Promise<(User & { email: string }) | null> {
    // Implement your database query logic here
    // Example: return await this.userRepository.findOne({ where: { email } });
  }

  /**
   * Find user by username (required for username-based authentication)
   */
  getUserByUsername(
    username: string,
  ): Promise<(User & { username: string }) | null> {
    // Implement your database query logic here
    // Example: return this.userRepository.findOne({ where: { username } });
  }

  /**
   * Find user by ID (required for token validation and user profile operations)
   */
  getUserById(id: EntityId): Promise<User | null> {
    // Implement your database query logic here
    // Example: return this.userRepository.findOne({ where: { id } });
  }

  /**
   * Create new user during registration (supports both local and OAuth registration)
   */
  signUpUser(
    userDto: Partial<User>,
    signUpType: AuthProvider,
    profile?: GoogleProfile,
  ): Promise<User | null> {
    // Implement user creation logic here
    // Handle password hashing for local registration
    // Handle OAuth profile data for social registration
    // Example: return this.createUser(userDto, signUpType, profile);
  }

  /**
   * Update existing user information (required for profile updates)
   */
  updateUserById(
    id: EntityId,
    userDto: Partial<User>,
    updatedBy: User,
  ): Promise<User | null> {
    // Implement user update logic here
    // Example: return this.userRepository.update(id, userDto);
  }
}

2. Create and export your user module

Create a module that provides your user service and makes it available for dependency injection.

import { Module } from "@nestjs/common";
import { UserService } from "./services";

@Module({
  providers: [UserService],
  // Export the service so it can be used by the auth module
  exports: [UserService],
})
export class UserModule {}

3. Register the authentication module in your app.module.ts

Configure the authentication module by providing your user service and setting up authentication options.

NOTE: All available configuration options can be found in the AuthOptions interface documentation.

import { Module } from "@nestjs/common";
import { AuthField, AuthMethod } from "@hichchi/nest-connector/auth";
import { HichchiAuthModule } from "@hichchi/nest-auth";
import { UserModule } from "./user/user.module";

@Module({
  imports: [
    // Register the authentication module with your user service
    HichchiAuthModule.register(
      {
        imports: [UserModule], // Import your user module
        useExisting: UserService, // Use your existing user service
      },
      {
        // Optional: Redis configuration for token caching and session management
        redis: {
          host: "localhost",
          port: 6379,
          prefix: "nest-auth", // Prefix for Redis keys
        },
        // JWT token configuration
        jwt: {
          secret: "your-super-secret-jwt-key-here", // Use a strong secret in production
          expiresIn: 86400, // Access token expires in 24 hours (in seconds)
          refreshSecret: "your-super-secret-refresh-key-here", // Use a different secret for refresh tokens
          refreshExpiresIn: 604800, // Refresh token expires in 7 days (in seconds)
        },
        authMethod: AuthMethod.JWT, // Use JWT-based authentication
        authField: AuthField.EMAIL, // Authenticate users by email address
        validationExceptionFactory: true, // Enable detailed validation error messages
      },
    ),
  ],
})
export class AppModule {}

4. Start using the authentication endpoints

Once configured, your application will automatically have the following authentication endpoints available under /auth:

Authentication Endpoints:

  • POST /auth/sign-up - Register a new user account
  • POST /auth/sign-in - Login with email/username and password
  • POST /auth/sign-out - Logout and invalidate tokens
  • POST /auth/refresh-token - Refresh access tokens using refresh token
  • POST /auth/get-auth-response - Get authentication response from an existing token
  • GET /auth/me - Get current user profile (requires authentication)
  • POST /auth/change-password - Change user password (requires authentication)
  • POST /auth/request-password-reset - Request password reset
  • POST /auth/reset-password-verify - Verify password reset token/code
  • POST /auth/reset-password - Reset password using reset token
  • POST /auth/resend-email-verification - Send verification email again
  • POST /auth/verify-email - Verify email address
  • GET /auth/google-sign-in - Initiate Google OAuth login (if configured)
  • GET /auth/google-callback - Google OAuth callback endpoint

NOTE: All available endpoints are also available from AuthEndpoint enum of the @hichchi/nest-connector package

Example Usage:

# Register a new user
curl -X POST http://localhost:3000/auth/sign-up \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "securePassword123"}'

# Login
curl -X POST http://localhost:3000/auth/sign-in \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "securePassword123"}'

# Access protected profile endpoint (include JWT token in Authorization header)
curl -X GET http://localhost:3000/auth/me \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE"

Your authentication system is now ready to use! 🎉

📋 Prerequisites

Before installing @hichchi/nest-auth, ensure you have:

Required Dependencies

  • Node.js: >= 18.0.0
  • NestJS: >= 11.0.0
  • TypeScript: >= 5.6.0

Peer Dependencies

npm install @nestjs/common @nestjs/core @nestjs/jwt @nestjs/passport
npm install passport passport-local passport-jwt
npm install bcrypt jsonwebtoken

Internal Dependencies

This package depends on:

npm install @hichchi/nest-connector @hichchi/nest-core @hichchi/utils

Optional Dependencies

For enhanced features:

# For Google OAuth
npm install passport-google-oauth20

Database Requirements

  • A user entity/model in your database
  • User service that implements basic CRUD operations
  • Fields for email/username and password storage

🌟 Overview

🎯 Your complete authentication toolkit for NestJS applications. From JWT tokens to Google OAuth, from Redis caching to encryption services - everything you need to secure your application with enterprise-grade authentication features.

✨ Features

🚀 Ready-to-Use Authentication Endpoints

  • 📝 User Registration - Complete sign-up flow with email verification
  • 🔐 User Login/Logout - Secure authentication with JWT tokens
  • 🔄 Token Refresh - Automatic token renewal for seamless user experience
  • 👤 User Profile Management - Get current user info and update profiles
  • 🔑 Password Management - Change password and reset password functionality
  • ✉️ Email Verification - Built-in email verification system
  • 🌐 Google OAuth Integration - Social login with Google authentication

🔐 Authentication Strategies

  • 🔑 JWT Authentication - Secure token-based authentication with customizable options
  • 👤 Local Authentication - Traditional username/password authentication
  • 🌐 Google OAuth 2.0 - Social authentication integration

🛡️ Route Protection

  • 🔒 JWT Auth Guard - Protect your routes with JWT token validation
  • 👮 Role-Based Access Control - Restrict access based on user roles with tenant-aware user typing support
  • 🎫 Permission-Based Access Control - Fine-grained permission system
  • 🌍 Google Auth Guard - Protect routes with Google OAuth

🎯 Helpful Decorators

  • 👤 @CurrentUser - Get the authenticated user in your controllers
  • 🏷️ @Roles - Define required roles for route access
  • 🎫 @Permission - Define required permissions for route access
  • 📋 @AuthInfo - Access authentication metadata

🔧 Configuration Options

  • 🔧 Flexible Module Setup - Easy configuration with your existing user service
  • Redis Caching - Optional Redis integration for improved performance
  • 🔒 Security Settings - Customizable JWT options, password requirements
  • 🌐 Multi-tenant Support - tenant-based authentication with normalized tenant slug claims in JWT payloads
  • 🔌 WebSocket Support - Real-time authentication for WebSocket connections

🚀 Usage

Using Guards

JwtAuthGuard

This guard is used to authenticate requests using JWT tokens. It validates JWT tokens from either the Authorization header (Bearer token) or cookies, depending on your authentication method configuration. The guard also supports automatic token refresh when using cookie-based authentication.

import { JwtAuthGuard, CurrentUser, AuthUser } from "@hichchi/nest-auth";
import { UseGuards, Post, Get, Body } from "@nestjs/common";

// In a controller - protect routes that require authentication
@UseGuards(JwtAuthGuard)
@Post()
create(@Body() dto: CreateUserDto, @CurrentUser() user: AuthUser): Promise<User | null> {
  return this.userService.save(dto);
}

// Get current user profile
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@CurrentUser() user: AuthUser): AuthUser {
  return user;
}

LocalAuthGuard

This guard is used to authenticate users with username/password credentials (local authentication). It validates that the required credentials (email/username and password) are provided in the request body before proceeding with authentication using the local strategy.

Usually used with @CurrentUser() decorator - the LocalAuthGuard handles the authentication part and returns the authenticated user to the request, and the decorator is used to access the authenticated user from the request.

import {
  AuthUser,
  CurrentUser,
  LocalAuthGuard,
  SignInDto
} from "@hichchi/nest-auth";
import { AuthEndpoint, AuthResponse } from "@hichchi/nest-connector/auth";
import { HttpSuccessStatus } from "@hichchi/nest-connector";
import { Post, HttpCode, UseGuards, Body } from "@nestjs/common";

// In a controller - for sign-in endpoint
@Post(AuthEndpoint.SIGN_IN)
@HttpCode(HttpSuccessStatus.OK)
@UseGuards(LocalAuthGuard)
signIn(
  @CurrentUser() authUser: AuthUser,
  @Body() signInDto: SignInDto,
): Promise<AuthResponse> {
  return this.authService.signIn(authUser, signInDto);
}

GoogleAuthGuard

This guard is used to authenticate users with Google OAuth 2.0. It handles the OAuth authentication flow, validates that Google authentication is properly configured, and manages authentication callbacks from Google's OAuth service. Requires Google OAuth configuration in your auth options.

import { GoogleAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Query } from "@nestjs/common";

// Initiate Google OAuth authentication
@UseGuards(GoogleAuthGuard)
@Get('google-sign-in')
googleSignIn(@Query('redirectUrl') redirectUrl: string): void {
  // This route initiates Google OAuth authentication
  // User will be redirected to Google's OAuth consent screen
}

// Handle Google OAuth callback
@UseGuards(GoogleAuthGuard)
@Get('google-callback')
googleCallback(): void {
  // This route handles the callback from Google after authentication
  // The guard processes the OAuth response and authenticates the user
}

Using Decorators

@CurrentUser

This decorator is used to extract the authenticated user information from the request context. It removes sensitive information like password and provides access to user details in controller methods. Requires authentication guard to be applied to the route.

import { CurrentUser, AuthUser, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Post, Body } from "@nestjs/common";

// Get current authenticated user
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@CurrentUser() user: AuthUser): AuthUser {
  return user; // Password is automatically removed
}

// Use current user in business logic
@UseGuards(JwtAuthGuard)
@Post('users')
createUser(@Body() dto: CreateUserDto, @CurrentUser() user: AuthUser): Promise<User> {
  return this.userService.save({ ...dto, createdBy: user.id });
}

@Roles

This decorator is used to define required roles for route access. Works with role-based access control to restrict endpoints based on user roles.

import { Roles, RoleGuard, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Delete, Put, Param, Body } from "@nestjs/common";

// Require admin role
@UseGuards(JwtAuthGuard, RoleGuard)
@Roles('admin')
@Delete(':id')
deleteUser(@Param('id') id: string): Promise<void> {
  return this.userService.delete(id);
}

// Require multiple roles (user must have at least one)
@UseGuards(JwtAuthGuard, RoleGuard)
@Roles('admin', 'moderator')
@Patch(':id')
updateUser(@Param('id') id: string, @Body() dto: UpdateUserDto): Promise<User> {
  return this.userService.update(id, dto);
}

@Permission

This decorator is used to define required permissions for route access. Provides fine-grained permission-based access control.

import { Permission, PermissionGuard, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Delete, Param } from "@nestjs/common";

// Require specific permission
@UseGuards(JwtAuthGuard, PermissionGuard)
@Permission('users:read')
@Get()
getUsers(): Promise<User[]> {
  return this.userService.findAll();
}

// Require multiple permissions
@UseGuards(JwtAuthGuard, PermissionGuard)
@Permission('users:write', 'users:delete')
@Delete(':id')
deleteUser(@Param('id') id: string): Promise<void> {
  return this.userService.delete(id);
}

@AuthInfo

This decorator is used to access authentication metadata and additional information about the current authentication context.

import { AuthInfo, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get } from "@nestjs/common";

// Access authentication metadata
@UseGuards(JwtAuthGuard)
@Get('session-info')
getSessionInfo(@AuthInfo() authInfo: any): any {
  return {
    tokenType: authInfo.tokenType,
    issuedAt: authInfo.iat,
    expiresAt: authInfo.exp,
    // Additional auth metadata
  };
}

@SocketId

This decorator is used to extract the socket ID from the authenticated user's token data in the request. It provides easy access to the socket ID within controller methods for WebSocket-related functionality. Requires authentication guard to be applied to the route.

import { SocketId, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Post, Body } from "@nestjs/common";

// Get socket ID for WebSocket operations
@UseGuards(JwtAuthGuard)
@Get('socket-info')
getSocketInfo(@SocketId() socketId: string): any {
  return {
    socketId,
    message: 'Socket ID retrieved successfully'
  };
}

// Use socket ID in business logic
@UseGuards(JwtAuthGuard)
@Post('users/:id/update')
updateUserWithSocket(@Param('id') id: string, @Body() dto: UpdateUserDto, @SocketId() socketId: string): Promise<User> {
  return this.userService.update(id, { ...dto, socketId });
}

@Tenant

This decorator is used to extract the tenant identifier from the incoming request headers using the configured tenant header key. It provides a simple way to access tenant context in controller methods for multi-tenant routing and business logic.

import { Tenant, JwtAuthGuard } from "@hichchi/nest-auth";
import { UseGuards, Get, Post, Body } from "@nestjs/common";

// Read tenant context from request headers
@UseGuards(JwtAuthGuard)
@Get('tenant-context')
getTenantContext(@Tenant() tenant: TenantSlug): any {
  return {
    tenant,
    message: 'Tenant resolved successfully'
  };
}

// Use tenant in service operations
@UseGuards(JwtAuthGuard)
@Post('users')
createTenantUser(@Body() dto: CreateUserDto, @Tenant() tenant: TenantSlug): Promise<User> {
  return this.userService.createForTenant(tenant, dto);
}

Using Extractors

cookieExtractor

This extractor function is used to extract JWT access tokens from request cookies. It's primarily used internally by the authentication system when using cookie-based authentication, but can also be used in custom authentication strategies.

import { cookieExtractor } from "@hichchi/nest-auth";
import { ExtractJwt } from "passport-jwt";
import { Request } from "express";

// Use with passport-jwt ExtractJwt.fromExtractors
const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromExtractors([cookieExtractor]),
  secretOrKey: "your-secret-key",
};

// Manual usage to extract token from request
function extractTokenFromCookies(request: Request): string | null {
  return cookieExtractor(request);
}

// Example in a custom strategy
@Injectable()
export class CustomJwtStrategy extends PassportStrategy(
  Strategy,
  "custom-jwt",
) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        cookieExtractor, // Extract from cookies first
        ExtractJwt.fromAuthHeaderAsBearerToken(), // Fallback to Authorization header
      ]),
      secretOrKey: process.env.JWT_SECRET,
    });
  }
}

Using Utilities

Configuration Validation Functions

These utility functions help validate authentication configuration during module setup to ensure all required options are properly configured.

validateRedisOptions

Validates Redis connection options to ensure either a URL or host is provided for establishing a connection.

import { validateRedisOptions } from "@hichchi/nest-auth";
import { RedisOptions } from "@hichchi/nest-core";

// Validate Redis configuration before using
const redisConfig: RedisOptions = {
  host: "localhost",
  port: 6379,
  prefix: "auth-cache",
};

try {
  validateRedisOptions(redisConfig);
  console.log("Redis configuration is valid");
} catch (error) {
  console.error("Invalid Redis configuration:", error.message);
}

// Example with URL-based configuration
const redisUrlConfig: RedisOptions = {
  url: "redis://localhost:6379",
};

validateRedisOptions(redisUrlConfig); // Will pass validation
validateJwtOptions

Validates JWT configuration options to ensure all required secrets and expiration times are provided.

import { validateJwtOptions } from "@hichchi/nest-auth";
import { JwtOptions } from "@hichchi/nest-auth";

// Validate JWT configuration
const jwtConfig: JwtOptions = {
  secret: "your-access-token-secret",
  expiresIn: 3600, // 1 hour
  refreshSecret: "your-refresh-token-secret",
  refreshExpiresIn: 604800, // 7 days
};

try {
  validateJwtOptions(jwtConfig);
  console.log("JWT configuration is valid");
} catch (error) {
  console.error("Invalid JWT configuration:", error.message);
}

// Example usage in module configuration
@Module({
  imports: [
    HichchiAuthModule.register(
      {
        /* user service config */
      },
      {
        jwt: jwtConfig, // This will be validated internally
        // other auth options...
      },
    ),
  ],
})
export class AppModule {}
validateUserServiceProvider

Validates that a user service implements all required methods based on the authentication configuration.

import { validateUserServiceProvider } from "@hichchi/nest-auth";
import { IUserService, AuthOptions } from "@hichchi/nest-auth";
import { AuthField } from "@hichchi/nest-connector/auth";

// Example user service implementation
@Injectable()
export class UserService implements IUserService {
  async getUserByEmail(email: string) {
    /* implementation */
  }
  async getUserByUsername(username: string) {
    /* implementation */
  }
  async getUserById(id: string) {
    /* implementation */
  }
  async signUpUser(userDto: any) {
    /* implementation */
  }
  async updateUserById(id: string, userDto: any) {
    /* implementation */
  }
}

// Validate the user service against auth configuration
const authOptions: AuthOptions = {
  authField: AuthField.EMAIL,
  jwt: {
    /* jwt config */
  },
  googleAuth: {
    /* google config */
  },
};

const userService = new UserService();

try {
  validateUserServiceProvider(userService, authOptions);
  console.log("User service implements all required methods");
} catch (error) {
  console.error("User service validation failed:", error.message);
}

User Management Functions

generateAuthUser

Generates an AuthUser object from cached user data and access token, combining user information with session details.

import { generateAuthUser } from "@hichchi/nest-auth";
import { CacheUser, AuthUser } from "@hichchi/nest-auth";

// Example cached user data
const cacheUser: CacheUser = {
  id: "user-123",
  firstName: "John",
  lastName: "Doe",
  email: "[email protected]",
  roles: ["user"],
  sessions: [
    {
      sessionId: "session-456",
      accessToken: "jwt-access-token-here",
      refreshToken: "jwt-refresh-token-here",
    },
  ],
};

// Generate AuthUser from cache and token
try {
  const authUser: AuthUser = generateAuthUser(
    cacheUser,
    "jwt-access-token-here",
  );

  console.log("Generated AuthUser:", {
    id: authUser.id,
    fullName: authUser.fullName, // 'John Doe' - automatically generated
    email: authUser.email,
    sessionId: authUser.sessionId,
    accessToken: authUser.accessToken,
    refreshToken: authUser.refreshToken,
  });
} catch (error) {
  console.error("Failed to generate AuthUser:", error.message);
}

// Example usage in a custom authentication service
@Injectable()
export class CustomAuthService {
  constructor(private cacheService: UserCacheService) {}

  async getAuthenticatedUser(accessToken: string): Promise<AuthUser> {
    // Get user from cache (implementation depends on your cache strategy)
    const cacheUser = await this.cacheService.getUserByToken(accessToken);

    if (!cacheUser) {
      throw new UnauthorizedException("User not found in cache");
    }

    // Generate AuthUser with session information
    return generateAuthUser(cacheUser, accessToken);
  }
}

🔧 Configuration Reference

Complete Configuration Options

// JWT authentication configuration options
interface JwtOptions {
  /** Secret key used to sign JWT access tokens */
  secret: string;
  /** Expiration time for access tokens in seconds */
  expiresIn: number;
  /** Secret key used to sign JWT refresh tokens */
  refreshSecret: string;
  /** Expiration time for refresh tokens in seconds */
  refreshExpiresIn: number;
}

// Google OAuth authentication configuration options
interface GoogleAuthOptions {
  /** Google OAuth client ID from Google Developer Console */
  clientId: string;
  /** Google OAuth client secret from Google Developer Console */
  clientSecret: string;
}

// Cookie configuration options
interface CookiesOptions {
  /** Secret key used for signing cookies */
  secret?: string;
  /** Controls how cookies are sent with cross-site requests */
  sameSite?: boolean | "lax" | "strict" | "none";
  /** Whether cookies should only be sent over HTTPS */
  secure?: boolean;
}

// Main authentication configuration options
interface AuthOptions {
  /**
   * Whether the application is running in production mode
   * @default false
   */
  isProd?: boolean;

  /**
   * Redis configuration for caching user sessions
   * When provided, user sessions will be stored in Redis
   */
  redis?: RedisOptions;

  /**
   * Secret key used for encrypting user sessions in cache
   * Required when using Redis caching with sensitive user data
   */
  sessionSecret?: string;

  /**
   * JWT configuration options (Required)
   */
  jwt: JwtOptions;

  /**
   * Google OAuth configuration options
   * When provided, enables Google OAuth authentication
   */
  googleAuth?: GoogleAuthOptions;

  /**
   * Cookie configuration options
   * Used when authMethod is set to AuthMethod.COOKIE
   */
  cookies?: CookiesOptions;

  /**
   * Whether to verify user email before allowing authentication
   * @default false
   */
  checkEmailVerified?: boolean;

  /**
   * URL to redirect to after email verification
   * Required when checkEmailVerified is true
   */
  emailVerifyRedirect?: string;

  /**
   * Password reset token expiration time in seconds
   * @default 3600 (1 hour)
   */
  passwordResetExp?: number;

  /**
   * Authentication method (JWT, Cookie, etc.)
   * @default AuthMethod.JWT
   */
  authMethod?: AuthMethod;

  /**
   * Field used for authentication (email, username, etc.)
   * @default AuthField.EMAIL
   */
  authField?: AuthField | string;

  /**
   * Custom DTO class for sign-up requests
   */
  signUpDto?: typeof SignUpDto;

  /**
   * Custom DTO class for user views
   */
  viewDto?: Type<ViewUserDto>;

  /**
   * Custom validation exception factory
   * @default false
   */
  validationExceptionFactory?:
    | boolean
    | ((errors: ValidationError[]) => HttpException);

  /**
   * Whether to disable sign-up functionality
   * @default false
   */
  disableSignUp?: boolean;

  /**
   * List of allowed domains for redirect URLs
   * Used to prevent open redirect vulnerabilities
   */
  allowedRedirectDomains?: string[];
}

Default Configuration

const defaultConfig: Partial<AuthOptions> = {
  isProd: false,
  checkEmailVerified: false,
  passwordResetExp: 3600, // 1 hour
  authMethod: AuthMethod.JWT,
  authField: AuthField.EMAIL,
  disableSignUp: false,
  validationExceptionFactory: false,
};

🔧 Development

Building

nx build nest-auth

Compile and bundle the authentication module for production use.

Testing

nx test nest-auth

Run comprehensive unit tests powered by Jest.


Made with ❤️ by Hichchi Dev

Hichchi Ecosystem Report Bug Request Feature

Empowering secure applications with enterprise-grade authentication, JWT tokens, OAuth integration, and role-based access control


📖 API Documentation

Complete technical reference for all classes, interfaces, methods, and types in this library.

Auto-generated by TypeDoc - Browse through detailed API references, code examples, and implementation guides below.


📋 API Table of Contents

Classes

AuthController

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:72

Authentication controller that handles all authentication-related endpoints.

This controller provides endpoints for user sign up, authentication, password management, email verification, and social authentication.

The default endpoint path is 'auth' but can be customized by extending this class:

Example

@Controller("custom-auth")
export class CustomAuthController extends AuthController {
  // Override existing methods or add new ones

  @Get("custom-endpoint")
  async customEndpoint() {
    return "Custom endpoint";
  }
}

See

  • Endpoint.AUTH - The default endpoint path constant used for this controller.
  • Endpoint - Contains all available endpoints for this module.

Constructors

Constructor
new AuthController(options, authService): AuthController;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:83

Creates an instance of AuthController.

Parameters

options

AuthOptions

The authentication options injected from AUTH_OPTIONS token

authService

AuthService

The authentication service

Returns

AuthController

See

Methods

changePassword()
changePassword(
   request,
   authUser,
   updatePasswordDto,
tenant?): Promise<User<string, string, TenantSlug>>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:485

Changes the password for the currently authenticated user.

This endpoint allows an authenticated user to change their password. It requires both the current password and the new password.

Parameters

request

Request

The Express request object

authUser

AuthUser

The authenticated user information (provided by JwtAuthGuard)

updatePasswordDto

UpdatePasswordDto

DTO containing the current and new passwords

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<User<string, string, TenantSlug>>

The updated user information

Example
// Client-side example
const response = await fetch("/auth/change-password", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer your-jwt-token",
  },
  body: JSON.stringify({
    currentPassword: "current-password",
    newPassword: "new-password",
  }),
});
// result:
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "[email protected]",
  "firstName": "John",
  "lastName": "Doe",
  "isVerified": true,
  "signUpType": "local"
}
See
  • AuthEndpoint.CHANGE_PASSWORD - The specific endpoint path segment for changing user passwords.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
getAuthResponse()
getAuthResponse(
   request,
   response,
   getAuthResponseDto,
tenant?): Promise<AuthResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:339

Gets a complete authentication response using an existing access token.

This endpoint allows clients to retrieve a complete authentication response using a previously issued JWT access token. It verifies the token, retrieves the associated user information, generates new tokens, and returns comprehensive authentication data.

Parameters

request

Request

The Express request object

response

Response

The Express response object for setting cookies

getAuthResponseDto

GetAuthResponseDto

DTO containing the JWT access token

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<AuthResponse>

Authentication response containing user info and tokens

Example
// Client-side example - using a previously obtained JWT token
const response = await fetch("/auth/get-auth-response", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    accessToken: "previously-issued-jwt-token",
  }),
});
const authData = await response.json();
// Result:
{
  "user": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "[email protected]",
    "firstName": "John",
    "lastName": "Doe",
    "isVerified": true,
    "signUpType": "google"
  },
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "accessTokenExpiresOn": "2025-06-24T15:12:45.123Z",
  "refreshTokenExpiresOn": "2025-07-24T10:12:45.123Z",
  "sessionId": "sess_abc123"
}
See
  • AuthEndpoint.GET_AUTH_RESPONSE - The specific endpoint path segment for retrieving authentication data.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
getCurrentUser()
getCurrentUser(
   request,
   authUser,
tenant?): Promise<User<string, string, TenantSlug> | null>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:431

Retrieves the currently authenticated user's information.

This endpoint returns the user information for the currently authenticated user. It requires a valid JWT token and is protected by the JwtAuthGuard.

Parameters

request

Request

The Express request object

authUser

AuthUser

The authenticated user information (provided by JwtAuthGuard)

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<User<string, string, TenantSlug> | null>

The current user's information or null if not found

Example
// Client-side example
const response = await fetch("/auth/me", {
  method: "GET",
  headers: {
    Authorization: "Bearer your-jwt-token",
  },
});
const user = await response.json();
// result:
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "[email protected]",
  "firstName": "John",
  "lastName": "Doe",
  "isVerified": true,
  "signUpType": "local"
}
See
  • AuthEndpoint.ME - The specific endpoint path segment for retrieving current user information.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
googleCallback()
googleCallback(
   response,
   authUser,
   state): void;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:276

Handles the callback from Google OAuth authentication.

This endpoint is called by Google after successful authentication. It extracts the redirect URL from the state parameter and redirects the user to that URL with the access token as a query parameter.

Parameters

response

Response

The Express response object for redirection

authUser

AuthUser

The authenticated user information (provided by GoogleAuthGuard)

state

string

JSON string containing the redirectUrl

Returns

void

This method doesn't return any content as it redirects to the client application

Throws

If there's an error processing the callback

Example
// This endpoint is not called directly from client code
// It's called by Google's OAuth service after user authenticates
// The flow typically is:
// 1. User clicks "Sign In with Google" link (pointing to googleSignIn endpoint)
// 2. User authenticates on Google's site
// 3. Google redirects to this callback URL
// 4. This method redirects to the original application with the token
See
  • AuthEndpoint.GOOGLE_CALLBACK - The specific endpoint path segment for Google OAuth callback processing.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
googleSignIn()
googleSignIn(_query): Promise<void>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:239

Initiates Google OAuth sign-in flow.

This endpoint redirects the user to Google's authentication page. The redirectUrl query parameter is used to determine where to redirect after successful authentication.

Parameters

_query

GoogleAuthRequestQuery

The query parameters from the request

Returns

Promise<void>

This method doesn't return any content as it redirects to Google

Example
// Client-side example - typically used as a link in your frontend
<a href="/auth/google-sign-in?redirectUrl=http://your-app.com/dashboard">
    Sign in with Google
</a>

Note: Recommended approach is to use a browser popup or new tab to call this API instead of a full page redirect. This allows smoother handling of the authentication flow and makes it easier to capture the callback response, especially in single-page applications (SPAs) or when working with cross-origin redirects.

See
  • AuthEndpoint.GOOGLE_SIGN_IN - The specific endpoint path segment for initiating Google OAuth flow.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
refreshTokens()
refreshTokens(
   request,
   refreshTokenDto,
   response,
tenant?): Promise<TokenResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:380

Refreshes the authentication tokens using a refresh token.

This endpoint allows clients to obtain new access and refresh tokens when their current access token expires, without requiring the user to log in again.

Parameters

request

Request

The Express request object

refreshTokenDto

RefreshTokenDto

DTO containing the refresh token

response

Response

The Express response object for setting cookies

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<TokenResponse>

New access and refresh tokens

Example
// Client-side example
const response = await fetch("/auth/refresh-token", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    refreshToken: "your-refresh-token",
  }),
});
const tokens = await response.json();
// tokens contains new accessToken and refreshToken
See
  • AuthEndpoint.REFRESH_TOKEN - The specific endpoint path segment for token refreshing.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
requestPasswordReset()
requestPasswordReset(
   request,
   requestResetDto,
tenant?): Promise<SuccessResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:629

Initiates the password reset process for a user.

This endpoint allows users to request a password reset by providing their email address. If the email exists in the system, a password reset link will be sent to that email.

Parameters

request

Request

The Express request object

requestResetDto

RequestResetDto

DTO containing the email address

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<SuccessResponse>

Success response indicating the reset email was sent

Example
// Client-side example
const response = await fetch("/auth/request-password-reset", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "[email protected]",
  }),
});
const result = await response.json();
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_PASSWORD_RESET_EMAIL_SENT",
  "message": "Password reset email sent successfully"
}
See
  • AuthEndpoint.REQUEST_PASSWORD_RESET - The specific endpoint path segment for requesting password resets.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
resendEmailVerification()
resendEmailVerification(
   request,
   resendEmailVerifyDto,
tenant?): Promise<SuccessResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:533

Resends the email verification link to the user.

This endpoint allows users to request a new email verification link if they didn't receive the original one or if it expired.

Parameters

request

Request

The Express request object

resendEmailVerifyDto

ResendEmailVerifyDto

DTO containing the email address

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<SuccessResponse>

Success response indicating the email was sent

Example
// Client-side example
const response = await fetch("/auth/resend-email-verification", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "[email protected]",
  }),
});
const result = await response.json();
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_EMAIL_VERIFICATION_SENT",
  "message": "Verification email sent successfully"
}
See
  • AuthEndpoint.RESEND_EMAIL_VERIFICATION - The specific endpoint path segment for resending verification emails.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
resetPassword()
resetPassword(
   request,
   resetPasswordDto,
tenant?): Promise<SuccessResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:722

Resets a user's password using a valid reset token.

This endpoint allows users to set a new password after verifying their reset token. It should be called after the token has been verified using the verifyResetPasswordToken endpoint.

Parameters

request

Request

The Express request object

resetPasswordDto

ResetPasswordDto

DTO containing the reset token and new password

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<SuccessResponse>

Success response indicating the password was reset

Example
// Client-side example
const response = await fetch("/auth/reset-password", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    token: "reset-token-from-email",
    password: "new-password",
  }),
});
const result = await response.json();
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_PASSWORD_RESET_SUCCESS",
  "message": "Password reset successfully"
}
See
  • AuthEndpoint.RESET_PASSWORD - The specific endpoint path segment for setting a new password after reset.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
signIn()
signIn(
   request,
   authUser,
   _signInDto,
   response,
tenant?): Promise<AuthResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:201

Authenticates a user with email/username and password.

This endpoint handles user sign in using local authentication strategy. It sets authentication cookies and returns user information with tokens.

Parameters

request

Request

The Express request object

authUser

AuthUser

The authenticated user information (provided by LocalAuthGuard)

_signInDto

SignInDto

The sign in credentials (not used directly as LocalAuthGuard handles validation)

response

Response

The Express response object for setting cookies

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<AuthResponse>

Authentication response containing user info and tokens

Example
// Client-side example
const response = await fetch("/auth/sign-in", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "[email protected]",
    password: "password123",
  }),
});
const authData = await response.json();
// Result:
{
  "user": {
    "id": "123e4567-e89b-12d3-a456-426614174000",
    "email": "[email protected]",
    "firstName": "John",
    "lastName": "Doe",
    "isVerified": true,
    "signUpType": "local"
  },
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "accessTokenExpiresOn": "2025-06-24T15:12:45.123Z",
  "refreshTokenExpiresOn": "2025-07-24T10:12:45.123Z",
  "sessionId": "sess_abc123"
}
See
  • AuthEndpoint.SIGN_IN - The specific endpoint path segment for user authentication.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
signOut()
signOut(
   request,
   authUser,
response): Promise<SuccessResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:774

Signs out the currently authenticated user.

This endpoint invalidates the user's authentication tokens and clears authentication cookies. It requires a valid JWT token and is protected by the JwtAuthGuard.

Parameters

request

Request

The Express request object

authUser

AuthUser

The authenticated user information (provided by JwtAuthGuard)

response

Response

The Express response object for clearing cookies

Returns

Promise<SuccessResponse>

Success response indicating the user was signed out

Example
// Client-side example
const response = await fetch("/auth/sign-out", {
  method: "POST",
  headers: {
    Authorization: "Bearer your-jwt-token",
  },
});
const result = await response.json();

// After this, the client should clear any stored tokens and redirect to the sign in page
localStorage.removeItem("accessToken");
localStorage.removeItem("refreshToken");
window.location.href = "/sign-in";
// result
{
  "statusCode": HttpSuccessStatus.OK,
  "code": AuthSuccessResponseCode.AUTH_200_SIGNED_OUT,
  "message": "Signed out successfully",
}
See
  • AuthEndpoint.SIGN_OUT - The specific endpoint path segment for user logout and token invalidation.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
signUp()
signUp(
   request,
   dto,
tenant?): Promise<User<string, string, TenantSlug>>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:137

Sign up a new user with the provided sign-up data.

This endpoint creates a new user account with the provided sign up data. If sign up is disabled in the auth options, it will throw a ForbiddenException.

Parameters

request

Request

The Express request object

dto

SignUpBody

The sign-up data transfer object containing user sign up information

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<User<string, string, TenantSlug>>

The newly created user

Throws

If sign up is disabled

Example
// Client-side example
const response = await fetch("/auth/sign-up", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    email: "[email protected]",
    password: "password123",
    firstName: "John",
    lastName: "Doe",
  }),
});
const user = await response.json();
// Result:
{
  "id": "123e4567-e89b-12d3-a456-426614174000",
  "email": "[email protected]",
  "firstName": "John",
  "lastName": "Doe",
  "isVerified": true,
  "signUpType": "local",
  "createdAt": "2025-06-24T10:12:45.123Z",
  "updatedAt": "2025-06-24T11:30:15.456Z"
}
See
  • AuthEndpoint.SIGN_UP - The specific endpoint path segment for user registration.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
verifyEmail()
verifyEmail(
   request,
   response,
   emailVerifyDto,
tenant?): Promise<void>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:573

Verifies a user's email address using the verification token.

This endpoint is accessed via a link sent to the user's email. It verifies the token and redirects the user to a configured URL with a query parameter indicating whether verification was successful.

Parameters

request

Request

The Express request object

response

Response

The Express response object for redirection

emailVerifyDto

EmailVerifyDto

DTO containing the verification token

tenant?

TenantSlug

The tenant slug (optional)

Returns

Promise<void>

This method doesn't return any content as it redirects to the configured URL

Example
This endpoint is typically accessed via a link in an email:

<a href="https://your-api.com/auth/verify-email?token=verification-token">
  Verify Email
</a>

The user will be redirected to the configured URL:
https://your-app.com/email-verification?verified=true
See
  • AuthEndpoint.VERIFY_EMAIL - The specific endpoint path segment for email verification processing.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.
verifyResetPasswordToken()
verifyResetPasswordToken(request, verifyDto): Promise<SuccessResponse>;

Defined in: libs/nest-auth/src/controllers/auth.controller.ts:675

Verifies a password reset token.

This endpoint allows clients to verify if a password reset token is valid before showing the password reset form to the user.

Parameters

request

Request

The Express request object

verifyDto

ResetPasswordTokenVerifyDto

DTO containing the reset token

Returns

Promise<SuccessResponse>

Success response indicating if the token is valid

Example
// Client-side example
const response = await fetch("/auth/reset-password-verify", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    token: "reset-token-from-email",
  }),
});
const result = await response.json();
// result:
{
  "statusCode": 200,
  "code": "AUTH_200_PASSWORD_RESET_TOKEN_VALID",
  "message": "Password reset token is valid"
}
See
  • AuthEndpoint.RESET_PASSWORD_VERIFY - The specific endpoint path segment for verifying password reset tokens.
  • AuthEndpoint - Enum containing all authentication-specific endpoint paths.
  • Endpoint.AUTH - The default endpoint path constant used for this controller.

Properties

authService

readonly

AuthService

The authentication service

libs/nest-auth/src/controllers/auth.controller.ts:85


AuthService

Defined in: libs/nest-auth/src/services/auth.service.ts:108

Core authentication service that provides comprehensive identity management functionality.

This service is responsible for handling all authentication-related operations within the application. It works alongside the AuthController to provide a complete authentication solution. The service delegates many operations to specialized services like JwtTokenService for token management, UserCacheService for session management, and TokenVerifyService for verification tokens.

Key features include:

  • User sign up and sign in with email/username and password
  • JWT token generation, validation, and refresh
  • Password management (change, reset, verify)
  • Email verification workflow
  • Social authentication (Google OAuth)
  • Session management with multi-device support
  • Token-based and cookie-based authentication modes

The service is designed to be flexible and configurable through the AuthOptions injection token, allowing applications to customize authentication behaviors. It also integrates with a user service provided by the application through the USER_SERVICE injection token, which handles user data storage.

Security features include:

  • Secure password hashing with bcrypt
  • Cryptographically secure token generation
  • Token expiration and refresh mechanisms
  • Protection against common authentication vulnerabilities

Example

// In a controller
@Controller("auth")
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Post("sign-up")
  async signUp(@Req() request: Request, @Body() signUpDto: SignUpDto) {
    return this.authService.signUp(request, signUpDto);
  }
}

See

  • AuthController The controller that exposes authentication endpoints using this service
  • JwtTokenService Service responsible for JWT token operations
  • UserCacheService Service that manages user session caching
  • TokenVerifyService Service that handles verification tokens
  • AuthOptions Configuration options for authentication behavior
  • IUserService Interface that user services must implement

Constructors

Constructor
new AuthService(
   options,
   userService,
   jwtTokenService,
   cacheService,
   tokenVerifyService): AuthService;

Defined in: libs/nest-auth/src/services/auth.service.ts:118

Creates an instance of AuthService.

Parameters

options

AuthOptions

The authentication options injected from AUTH_OPTIONS token

userService

IUserService

The user service injected from USER_SERVICE token

jwtTokenService

JwtTokenService

The JWT token service for token operations

cacheService

UserCacheService

The user cache service for storing user sessions

tokenVerifyService

TokenVerifyService

The token verification service for email and password reset tokens

Returns

AuthService

Methods

authenticate()
authenticate(
   request,
   username,
   password,
tenant?): Promise<AuthUser>;

Defined