Triển khai Login With Google ( NextJs - NestJs)

date
Oct 22, 2025
slug
trien-khai-login-with-google
status
Published
tags
NextJs
Backend
NestJs
summary
Cách triển khai Login với Google
type
Post
Next.js (Frontend) ├── Giao diện nút "Login with Google" ├── Gọi endpoint /auth/google (backend) └── Nhận JWT / session NestJS (Backend) ├── Passport + Google OAuth2 Strategy ├── Endpoint callback xử lý token Google └── Trả JWT token về frontend
  1. Setting google cloud
Authorized redirect URIs
  1. NestJs
@Get('google') @UseGuards(AuthGuard('google')) @ApiOperation({ summary: 'Initiate Google OAuth login' }) @ApiResponse({ status: 302, description: 'Redirect to Google OAuth' }) async googleAuth() { // Passport sẽ tự động redirect đến Google OAuth } @Get('google/callback') @UseGuards(AuthGuard('google')) @ApiOperation({ summary: 'Google OAuth callback' }) @ApiResponse({ status: 302, description: 'Redirect to frontend with token' }) async googleAuthRedirect(@Request() req: any, @Res() res: Response) { const user = req.user; const result = await this.authService.login(user); // Redirect đến frontend với token const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3001'; const redirectUrl = `${frontendUrl}/auth/callback?token=${result.access_token}&refresh_token=${result.refresh_token}`; res.redirect(redirectUrl); }