How to Use Passport Google Strategy in Express for Authentication
To use
passport-google-oauth20 strategy in Express, install the package, configure Passport with your Google client ID and secret, then set up routes to handle Google login and callback. Use passport.authenticate('google') middleware to start authentication and handle user info in the callback.Syntax
The passport-google-oauth20 strategy requires you to create a new GoogleStrategy instance with your Google OAuth credentials and a callback function. You then use passport.use() to register this strategy. In Express routes, use passport.authenticate('google', options) to start login and handle the callback.
- clientID: Your Google app client ID.
- clientSecret: Your Google app client secret.
- callbackURL: URL Google redirects to after login.
- verify callback: Function to process user profile and tokens.
javascript
const GoogleStrategy = require('passport-google-oauth20').Strategy; const passport = require('passport'); const express = require('express'); const app = express(); passport.use(new GoogleStrategy({ clientID: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', callbackURL: '/auth/google/callback' }, (accessToken, refreshToken, profile, done) => { // Process user profile here done(null, profile); })); // Express route to start Google login app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] })); // Callback route after Google login app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => { res.redirect('/'); });
Example
This example shows a simple Express app using Passport Google Strategy to authenticate users with Google. It includes session setup, Passport initialization, and routes to login and handle callback.
javascript
import express from 'express'; import session from 'express-session'; import passport from 'passport'; import { Strategy as GoogleStrategy } from 'passport-google-oauth20'; const app = express(); // Session setup app.use(session({ secret: 'secret', resave: false, saveUninitialized: true })); // Passport init app.use(passport.initialize()); app.use(passport.session()); // Serialize user to session passport.serializeUser((user, done) => done(null, user)); passport.deserializeUser((obj, done) => done(null, obj)); // Google Strategy passport.use(new GoogleStrategy({ clientID: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', callbackURL: '/auth/google/callback' }, (accessToken, refreshToken, profile, done) => { return done(null, profile); })); // Route to start Google login app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] })); // Callback route app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => { res.send(`<h1>Hello, ${req.user.displayName}</h1><p>Email: ${req.user.emails[0].value}</p>`); }); // Start server app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Output
Server running on http://localhost:3000
// After successful login, browser shows:
// <h1>Hello, [User's Google Name]</h1>
// <p>Email: [User's Google Email]</p>
Common Pitfalls
- Forgetting to enable OAuth consent screen in Google Cloud Console causes errors.
- Not setting correct
callbackURLmatching Google Console settings leads to redirect failures. - Missing
scopeinpassport.authenticatemeans no user info is returned. - Not calling
passport.initialize()andpassport.session()middleware breaks authentication flow. - Not serializing and deserializing user properly causes session issues.
javascript
/* Wrong: Missing scope and callbackURL mismatch */ passport.use(new GoogleStrategy({ clientID: 'ID', clientSecret: 'SECRET', callbackURL: '/wrong/callback' }, (accessToken, refreshToken, profile, done) => done(null, profile))); app.get('/auth/google', passport.authenticate('google')); // No scope /* Right: Correct callbackURL and scope */ passport.use(new GoogleStrategy({ clientID: 'ID', clientSecret: 'SECRET', callbackURL: '/auth/google/callback' }, (accessToken, refreshToken, profile, done) => done(null, profile))); app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
Quick Reference
- Install:
npm install passport passport-google-oauth20 express-session - Initialize Passport: Use
passport.initialize()andpassport.session()middleware. - GoogleStrategy: Provide
clientID,clientSecret, andcallbackURL. - Routes: Use
passport.authenticate('google', { scope: [...] })to start login and handle callback. - Session: Implement
serializeUseranddeserializeUser.
Key Takeaways
Install and configure passport-google-oauth20 with your Google app credentials.
Use passport.authenticate('google', { scope: ['profile', 'email'] }) to start Google login.
Set up callback route matching Google Console's authorized redirect URI.
Initialize Passport and session middleware properly in Express.
Handle user serialization and deserialization for session support.