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 🙏

© 2025 – Pkg Stats / Ryan Hefner

nestjs-google-auth-guard

v0.1.3

Published

Google Auth Guard for NestJS

Downloads

20

Readme

nestjs-google-auth-guard

A NestJS module for authenticating requests using Google OAuth tokens. Provides flexible options for token extraction, context filtering, and custom validation, with support for both global and per-controller guard application.

Features

  • Validates Bearer tokens in the Authorization header using Google Auth and your provided client_id.
  • Supports custom token extraction (for non-HTTP or custom scenarios).
  • Allows filtering which contexts are validated (e.g., skip health checks).
  • Optionally ignores validation if no token is present for a context.
  • Supports custom validation logic after Google login.
  • Provides easy access to Google login ticket via dependency injection.
  • Can be applied globally or per-controller.

Installation

npm install nestjs-google-auth-guard

Usage

1. Register the Module

import { GoogleAuthModule } from 'nestjs-google-auth-guard';

@Module({
  imports: [
    GoogleAuthModule.forRoot({
      clientID: 'YOUR_GOOGLE_CLIENT_ID',
      // Optional advanced options below
      // globalGuards: true,
      // contextFilter: (ctx) => true,
      // extractToken: (ctx) => customTokenExtractor(ctx),
      // canIgnoreMissingToken: (ctx) => false,
      // validate: async (ticket) => true,
    }),
  ],
})
export class AppModule {}

2. Protect Controllers

  • Global Guards: If globalGuards is true, all controllers are protected unless filtered out by contextFilter.
  • Per-Controller: If globalGuards is false (default), use the @UseGoogleAuth() decorator on each controller you want to protect.
import { UseGoogleAuth } from 'nestjs-google-auth-guard';

@UseGoogleAuth()
@Controller('my-protected')
export class MyProtectedController {}

Example: Exclude HealthCheckController from Global Guards

To apply Google authentication globally but exclude a health check controller, use the contextFilter option with context.getClass():

import { Module } from '@nestjs/common';
import { GoogleAuthModule } from 'nestjs-google-auth-guard';
import { HealthCheckController } from './health-check.controller';
import { AppController } from './app.controller';

@Module({
  imports: [
    GoogleAuthModule.forRoot({
      clientID: 'YOUR_GOOGLE_CLIENT_ID',
      globalGuards: true,
      contextFilter: (context) => context.getClass() !== HealthCheckController,
    }),
  ],
  controllers: [AppController, HealthCheckController],
})
export class AppModule {}

This will apply Google authentication to all controllers except HealthCheckController.

3. Access Google Login Info

Inject GoogleAuthInfo to access the Google login ticket and token for the current request:

import { GoogleAuthInfo } from 'nestjs-google-auth-guard';

@Injectable()
export class MyService {
  constructor(private readonly authInfo: GoogleAuthInfo) {}

  getUserEmail(): string | undefined {
    return this.authInfo.getLoginTicket()?.getPayload()?.email;
  }
}

Options

  • clientID (required): Your Google OAuth client ID.
  • globalGuards (default: false): If true, guards are applied globally.
  • contextFilter(context): Filter which contexts are validated (e.g., skip health checks).
  • extractToken(context): Custom function to extract the token (for non-HTTP or custom scenarios).
  • canIgnoreMissingToken(context): If true, skips validation if no token is present for the context.
  • validate(ticket): Custom validation logic after Google login.

AsyncLocalStorage Caveat

GoogleAuthInfo uses AsyncLocalStorage to store login information. If any guard with an async canActivate runs before GoogleAuth, async context may be lost (Node.js limitation).

How to avoid this:

  • Use the validate option to store the login ticket in a safe async local storage if needed (one you initialize before any async guard).
  • Avoid having async guards before GoogleAuth.
  • Alternatively, you can manually set PreGoogleAuthGuard as one of the first guards to be executed. This ensures the async context is established before any other async guard runs, preserving access to login information throughout the request lifecycle.

License

MIT