NestJS is a popular framework for building scalable and maintainable server-side applications using TypeScript. It provides a solid foundation for developing Node.js applications with a modular architecture and a focus on dependency injection.

Passport is a flexible authentication middleware for Node.js that is often used in conjunction with frameworks like NestJS. It provides a simple and consistent way to handle authentication strategies, including OAuth2, which is a widely used protocol for authentication and authorization.

To integrate Google OAuth2 with Passport in a NestJS application, you’ll need to perform the following steps:

  1. Install the required dependencies:
  2. npm install @nestjs/passport passport passport-google-oauth20

Create a Google OAuth2 strategy file. In this file, you’ll configure Passport to use the Google OAuth2 strategy and define the necessary callback functions. For example, create a file named google.strategy.ts with the following content:

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private readonly configService: ConfigService) {
    super({
      clientID: configService.get('GOOGLE_CLIENT_ID'),
      clientSecret: configService.get('GOOGLE_CLIENT_SECRET'),
      callbackURL: configService.get('GOOGLE_CALLBACK_URL'),
      scope: ['email', 'profile'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: any,
    done: VerifyCallback,
  ): Promise<any> {
    // Here, you can handle the validation and user creation logic.
    // The `profile` object will contain user information returned by Google.
    // You can use this information to find or create a user in your application's database.
    // The `done` callback should be called with the user object.
    // For example:
    // const user = await this.userService.findOrCreateUser(profile);
    // done(null, user);
  }
}

Note: In this example, we’re using the ConfigService from @nestjs/config to retrieve the necessary configuration values from environment variables. Make sure you have the corresponding environment variables (GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and GOOGLE_CALLBACK_URL) properly set.

3. Register the GoogleStrategy in your NestJS application. Open the app.module.ts file and add the following lines:

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { GoogleStrategy } from './google.strategy';

@Module({
  imports: [PassportModule],
  providers: [GoogleStrategy],
})
export class AppModule {}

4. Configure the authentication routes in a dedicated authentication controller. For example, create a file named auth.controller.ts with the following content:

import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
  @Get('google')
  @UseGuards(AuthGuard('google'))
  googleLogin() {
    // This route will initiate the Google OAuth2 flow
    // and redirect the user to the Google login page.
  }

  @Get('google/callback')
  @UseGuards(AuthGuard('google'))
  googleCallback(@Req() req) {
    // This route is the callback URL registered with Google.
    // Passport