@alpha018/nestjs-firebase-auth

中文文档
4.0.0发布于 2026/10/24MITTypeScriptCommonJS构建来源已验证近 30 天下载 2053

NestJS Firebase library and Role based guard for authentication with some utils functions

原始使用文档
文档目录20 节
  1. NestJS Passport Strategy for Firebase Auth using Firebase A…
  2. Table of Contents
  3. Installation
  4. Usage
  5. Import The Module
  6. Parameter Options
  7. Auth Guard Without Role Validation
  8. Auth Guard With Role Validation
  9. Claim-Based Authorization (Fine-Grained)
  10. Controller-Level Authentication with Method-Level Authoriza…
  11. Additional Information
  12. Migration Guide (v2.0.0)
  13. Migration Guide (v1.9.x)
  14. 1. Replace RolesGuard with @Roles
  15. 2. Replace UseGuards(FirebaseGuard) with @Auth
  16. Why migrate?
  17. Documentation
  18. Resources
  19. Stay in touch
  20. License

NestJS Firebase Auth

NestJS Passport Strategy for Firebase Auth using Firebase Admin SDK, which includes the Firebase SDK library for use.

Check out the Wiki for full documentation and guides!

Table of Contents

⚠️ Breaking change in v2.0.0: the minimum required Node.js version is now 22.12, and the bundled Firebase Admin SDK moved to v14. See the v2.0.0 Migration Guide before upgrading.

Installation

npm i @alpha018/nestjs-firebase-auth firebase-admin

Usage

Import The Module

To use Firebase authentication in your application, import the module into your main module.

import { FirebaseAdminModule } from '@alpha018/nestjs-firebase-auth';

@Module({
  imports: [
    ...
      FirebaseAdminModule.forRootAsync({
        imports: [ConfigModule],
        useFactory: (configService: ConfigService) => ({
          // SELECT ONLY ONE: BASE64 OR OPTIONS (Firebase Options)!
          base64: configService.get('FIREBASE_SERVICE_ACCOUNT_BASE64'), // Base64 encoded service account JSON string
          options: {}, // Use this if not using base64
          auth: {
            config: {
              extractor: ExtractJwt.fromAuthHeaderAsBearerToken(), // Choose your extractor from the Passport library
              checkRevoked: true, // Set to true if you want to check for revoked Firebase tokens
              validateRole: true, // Set to true if you want to validate user roles
              useLocalDecode: true, // Set to true to resolve roles and claims locally from the token, without a Firebase call
              rolesClaimKey: 'user_roles' // Set the name of the key within the Firebase custom claims that stores user roles
            },
          },
        }),
        inject: [ConfigService],
      }),
    ...
  ],
})

Parameter Options

ParameterTypeRequiredDescription
base64stringYes*Base64 encoded service account JSON string. Required if options is not provided.
optionsobjectYes*Firebase Admin SDK configuration options. Required if base64 is not provided.
auth.config.extractorfunctionOptionalA custom extractor function from the Passport library to extract the token from the request.
auth.config.checkRevokedbooleanOptionalSet to true to check if the Firebase token has been revoked. Defaults to false.
auth.config.validateRolebooleanOptionalSet to true to validate user roles using Firebase custom claims. Defaults to false.
auth.config.useLocalDecodebooleanOptionalSet to true to validate roles and claims using the values already decoded from the JWT token, instead of fetching them from Firebase. Defaults to false. Note: If you update the claims, previously issued tokens may still contain outdated values and remain valid.
auth.config.useLocalRolesbooleanOptionalSet to true to validate user roles using local custom claims inside the JWT token. Defaults to false. Note: If you update the claims, previously issued tokens may still contain outdated roles and remain valid. (deprecated, use useLocalDecode)
auth.config.rolesClaimKeystringOptionalThe name of the key within the Firebase custom claims that stores user roles. Defaults to 'roles'. This allows you to customize the property name for roles in your custom claims object.
auth.config.claimsClaimKeystringOptionalThe name of the key within the Firebase custom claims that stores fine-grained claims. Defaults to 'permissions'. Note: Firebase caps the combined size of all custom claims at ~1000 bytes once serialized, shared across rolesClaimKey, claimsClaimKey, and anything else stored there. With many fine-grained claims across several domains, use short claim codes instead of long descriptive strings to stay under that budget.

Auth Guard Without Role Validation

To protect an endpoint without validating user roles, use the Auth Guard to ensure the Firebase user's token is valid.

import { Auth, FirebaseProvider } from '@alpha018/nestjs-firebase-auth';

export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @Auth() // This line protects your endpoint with Firebase Auth
  @Get()
  mainFunction() {
    return 'Hello World';
  }
}

Auth Guard With Role Validation

To enforce role-based access control, you need to set role-based custom claims in Firebase. Here's how you can set roles for a user using setClaimsRoleBase:

import { FirebaseProvider } from '@alpha018/nestjs-firebase-auth';

enum Roles {
  ADMIN,
  USER,
}

@Controller('')
export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @Get()
  async setUserRoles() {
    await this.firebaseProvider.setClaimsRoleBase<Roles>(
      'some-firebase-uid', // The UID of the user you want to set roles for
      [Roles.ADMIN]
    );
    return { status: 'ok' }
  }
}

Then, use the Auth Guard with role validation to check if a user has the necessary permissions to access an endpoint:

import { Roles } from '@alpha018/nestjs-firebase-auth';
enum Roles {
  ADMIN,
  USER,
}

@Controller('')
export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @Roles(Roles.ADMIN, Roles.USER) // This line checks the custom claims of the Firebase user AND ensures the user is authenticated (implicitly applies FirebaseGuard)
  @Get()
  mainFunction() {
    return 'Hello World';
  }
}

Claim-Based Authorization (Fine-Grained)

@RequireClaims checks access finer than roles: the user must hold every listed claim, not just one. It reads a separate custom-claims key (permissions by default, configurable via claimsClaimKey).

import { FirebaseProvider } from '@alpha018/nestjs-firebase-auth';

enum UsersClaim {
  READ = 'users:read',
  WRITE = 'users:write',
}

@Controller('')
export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @Get()
  async setUserClaims() {
    await this.firebaseProvider.setClaimsPermissionBase<UsersClaim>(
      'some-firebase-uid', // The UID of the user you want to set claims for
      [UsersClaim.READ, UsersClaim.WRITE],
    );
    return { status: 'ok' }
  }
}

Then, use @RequireClaims to check that a user holds every required claim to access an endpoint:

import { RequireClaims } from '@alpha018/nestjs-firebase-auth';

enum UsersClaim {
  READ = 'users:read',
  WRITE = 'users:write',
}

@Controller('')
export class AppController {
  @RequireClaims(UsersClaim.READ, UsersClaim.WRITE) // Requires BOTH claims AND ensures the user is authenticated (implicitly applies FirebaseGuard)
  @Get()
  mainFunction() {
    return 'Hello World';
  }
}

@RequireClaims is generic, so claims from different domains (UsersClaim, InvoicesClaim, ReportsClaim, ...) can coexist as plain strings in the same custom-claims array. It also combines with roles and policies on a single route through @Auth({ roles, claims, policies }).

Controller-Level Authentication with Method-Level Authorization

You can apply authentication at the controller level using @Auth() and then define specific roles for individual routes using @Roles(). The library is optimized to prevent redundant token verification in this scenario.

import { Auth, Roles } from '@alpha018/nestjs-firebase-auth';

enum AppRoles {
  ADMIN,
  USER,
}

@Auth() // Protects all routes in this controller (ensures valid token)
@Controller('users')
export class UsersController {
  
  @Get('profile')
  getProfile() {
    // Accessible by any authenticated user
    return { status: 'ok' };
  }

  @Roles(AppRoles.ADMIN) // Adds specific authorization requirement
  @Get('admin-dashboard')
  getAdminDashboard() {
    // Accessible ONLY by authenticated users with ADMIN role
    return { status: 'secure' };
  }
}

Additional Information

To retrieve the Decoded ID Token and role claims within a protected route, use the @FirebaseUser and @FirebaseRolesClaims parameter decorators.

import {
  FirebaseProvider,
  FirebaseUser,
  FirebaseRolesClaims,
  Roles,
} from '@alpha018/nestjs-firebase-auth';

import { DecodedIdToken } from 'firebase-admin/auth';

enum Roles {
  ADMIN,
  USER,
}

@Controller('')
export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @Roles(Roles.ADMIN, Roles.USER)
  @Get()
  async mainFunction(
    @FirebaseUser() user: DecodedIdToken,
    @FirebaseRolesClaims() claims: Roles[],
  ) {
    return {
      user,
      claims
    };
  }
}

Difference Between @FirebaseUser and @FirebaseRolesClaims

Note: Starting from version >=1.7.x, these two decorators are explicitly separated to avoid confusion (see issue #11):

  • @FirebaseUser() → Returns the full decoded token (DecodedIdToken).
  • @FirebaseRolesClaims() → Returns only the custom role claims (roles/permissions) defined for the user.

This separation ensures that developers can access both the raw Firebase user object and the role/claims information independently.

Migration Guide (v2.0.0)

v2.0.0 upgrades the bundled Firebase Admin SDK from v13 to v14. This library's own API is unchanged; the breaking changes come from the SDK:

ChangeAction required
Minimum Node.js is now 22.12Upgrade your runtime — Node.js 20 is end-of-life
auth namespace removed from the firebase-admin rootImport DecodedIdToken from firebase-admin/auth

➡️ Full details, including Jest configuration, are in the Migrations guide.

Migration Guide (v1.9.x)

To improve semantic clarity and developer experience, direct usage of guards was deprecated in favor of more descriptive decorators. As of v3.0.0, RolesGuard and the public FirebaseGuard export have been removed entirely — see the Migrations guide.

1. Replace RolesGuard with @Roles

Removed in v3.0.0:

@UseGuards(FirebaseGuard) // or alone if global
@RolesGuard(Roles.ADMIN)

New Way:

@Roles(Roles.ADMIN)

Note: @Roles automatically applies the authentication guard.


2. Replace UseGuards(FirebaseGuard) with @Auth

Removed in v3.0.0:

@UseGuards(FirebaseGuard)

New Way:

@Auth()

Why migrate?

  • Better readability: @Auth vs @UseGuards(FirebaseGuard) clearly states intent.
  • Optimized Performance: The new decorators use an optimized guard that prevents redundant token verification checks when composing controllers and methods.

Documentation

For more detailed information, guides, and advanced examples, please visit our Project Wiki.

Resources

Check out a few resources that may come in handy when working with NestJS:

  • Visit the NestJS Documentation to learn more about the framework.
  • Visualize your application graph and interact with the NestJS application in real-time using NestJS Devtools.

Stay in touch

License

Nest is MIT licensed.

版本与发布记录

@alpha018/nestjs-firebase-auth 共发布 20 个版本,首次发布于 2024/09/03;过去 12 个月发布了 9 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.0.0latest2026/10/2414 天前
3.0.02026/08/262 个月前
2.0.12026/08/172 个月前
2.0.02026/07/213 个月前
1.11.02026/03/078 个月前
1.10.02026/01/0410 个月前

关于 @alpha018/nestjs-firebase-auth 的常见问题

@alpha018/nestjs-firebase-auth 是什么?

NestJS Firebase library and Role based guard for authentication with some utils functions

如何安装 @alpha018/nestjs-firebase-auth?

在项目目录运行 npm install @alpha018/nestjs-firebase-auth,或使用 pnpm add / yarn add / bun add。

@alpha018/nestjs-firebase-auth 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@alpha018/nestjs-firebase-auth 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@alpha018/nestjs-firebase-auth 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@alpha018/nestjs-firebase-auth 可以商用吗?

@alpha018/nestjs-firebase-auth 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@alpha018/nestjs-firebase-auth 的下载量有多少?

根据 npm 官方下载统计,@alpha018/nestjs-firebase-auth 在 2026/10/06 – 2026/11/04 这 30 天内被下载 2,053 次,日均约 68 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@alpha018/nestjs-firebase-auth 还在维护吗?

最新版本 4.0.0 发布于 2026/10/24(14 天前);至今共发布 20 个版本,其中过去 12 个月发布了 9 个;首次发布于 2024/09/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。