Script Valley
Authentication From Scratch
OAuth 2.0 and Social LoginLesson 4.2

Setting up Google OAuth with Passport.js

passport-google-oauth20, Google Cloud Console setup, client ID, client secret, callback URL, GoogleStrategy configuration, serializeUser, deserializeUser

Google Cloud Setup

Before writing code, create OAuth credentials in the Google Cloud Console. Set the authorized redirect URI to http://localhost:3000/auth/google/callback during development. Copy the Client ID and Client Secret into your .env.

npm install passport passport-google-oauth20 express-session
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: '/auth/google/callback'
}, async (accessToken, refreshToken, profile, done) => {
  // Find or create user in your DB
  let user = await db.findUserByGoogleId(profile.id);
  if (!user) {
    user = await db.createUser({
      googleId: profile.id,
      email: profile.emails[0].value,
      name: profile.displayName
    });
  }
  return done(null, user);
}));

passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser(async (id, done) => {
  const user = await db.findUserById(id);
  done(null, user);
});

serializeUser decides what goes into the session (just the user ID). deserializeUser reconstructs the full user object from the session on each request.

Up next

How to link social accounts to existing users

Sign in to track progress