Skip to content

NestJS OAuth

OAuth lets users sign in with Google, GitHub, or other identity providers. Nest + Passport OAuth strategies handle the redirect dance and return a profile you can map to a local user.

OAuth Redirect Flow in Nest

A typical flow: client hits GET /auth/google, Nest redirects to Google, Google redirects back to GET /auth/google/callback, Passport validates the profile, and your AuthService finds or creates a local user then issues app tokens.

@Get('google')
@UseGuards(AuthGuard('google'))
googleAuth() {}

@Get('google/callback')
@UseGuards(AuthGuard('google'))
googleCallback(@Req() req) {
  return this.authService.loginWithOAuth(req.user);
}

Empty handler methods are normal: the guard/strategy performs the redirect and profile validation before your callback method runs.

Google Strategy Skeleton

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

  validate(accessToken: string, refreshToken: string, profile: any) {
    return { provider: 'google', providerId: profile.id, email: profile.emails[0].value };
  }
}
  • Store OAuth client IDs/secrets in environment variables.
  • Map provider profile id + email to your users table carefully (account linking).
  • Issue your own JWT after OAuth success rather than trusting provider tokens forever.
  • Validate callback URLs registered in the provider console match your Nest routes.

OAuth Nest Cheatsheet

Moving parts for social login.

Piece Purpose
Provider strategy Talks to Google/GitHub/etc.
Auth start route Redirects user to provider
Callback route Receives provider redirect
User linking Find/create local user from profile
App JWT issuance Return tokens for your API

Account Linking Pitfalls

If an email already exists locally, decide whether to auto-link OAuth identity or require proof of ownership. Blind auto-linking can be an account takeover vector.

Request Minimal Scopes

Only request the OAuth scopes you need (email, profile). Extra scopes increase user friction and security review burden.

Common Mistakes

  • Hard-coding client secrets in source control.
  • Trusting provider email as verified without checking provider claims.
  • Forgetting HTTPS callback URLs in production provider settings.
  • Skipping your own session/JWT after OAuth and calling provider APIs on every request.

Key Takeaways

  • Passport OAuth strategies implement the redirect and callback flow in Nest.
  • Map provider profiles to local users carefully, then issue your own tokens.
  • Keep client secrets and callback URLs in configuration.
  • Request only the OAuth scopes you actually need.

Pro Tip

Log OAuth failures with provider error query params during development, but never expose client secrets or raw provider tokens in API error responses.