OAuth 2.0 Login with Google in Node.js (Passport.js)

Implementing third-party authentication via OAuth 2.0 allows users to securely log into your application using their existing credentials (such as Google, GitHub, or Auth0) without exposing sensitive passwords. In the Node.js ecosystem, Passport.js is the industry-standard authentication middleware, providing modular strategies for handling complex authorization flows.

This comprehensive guide walks through setting up a Google OAuth 2.0 authentication pipeline in an Express.js application using Passport.js, complete with session serialization and protected routes.

1. Project Setup and Dependencies

First, initialize a new Node.js project and install the essential dependencies required for Express, Passport, Google OAuth strategy, and express sessions.

C
# Initialize Node.js project
mkdir google-auth-demo && cd google-auth-demo
npm init -y

# Install required packages
npm install express passport passport-google-oauth20 express-session dotenv

2. Configuring Google Cloud Credentials

Before writing code, you must register your application in the Google Cloud Console to obtain your OAuth 2.0 Client ID and Client Secret:

  • Go to the Google Cloud Console and create a new project.
  • Navigate to APIs & Services > Credentials and click Create Credentials > OAuth client ID.
  • Select Web application as the application type.
  • Add your authorized redirect URI (e.g., http://localhost:3000/auth/google/callback).
  • Copy your generated Client ID and Client Secret into a local .env file.
C
# .env configuration
PORT=3000
GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
SESSION_SECRET=your_super_secret_session_key

3. Implementing Passport and Express Server

Create an index.js file to configure Express, session management, Passport Google Strategy, and authentication routing.

C
require('dotenv').config();
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const session = require('express-session');

const app = express();

// Session Middleware Configuration
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}));

// Initialize Passport and Session
app.use(passport.initialize());
app.use(passport.session());

// Passport Serialization
passport.serializeUser((user, done) => {
    done(null, user);
});

passport.deserializeUser((obj, done) => {
    done(null, obj);
});

// Configure Google Strategy
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: '/auth/google/callback'
},
(accessToken, refreshToken, profile, done) => {
    // Here you would typically save or find the user in your database
    return done(null, profile);
}));

// Routes
app.get('/', (req, res) => {
    res.send('<h1>Home</h1><a href="/auth/google">Login With Google</a>');
});

// Trigger Google Authentication
app.get('/auth/google', 
    passport.authenticate('google', { scope: ['profile', 'email'] })
);

// Google Callback Route
app.get('/auth/google/callback', 
    passport.authenticate('google', { failureRedirect: '/' }),
    (req, res) => {
        // Successful authentication, redirect to dashboard
        res.redirect('/profile');
    }
);

// Protected Profile Route
app.get('/profile', (req, res) => {
    if (!req.isAuthenticated()) {
        return res.redirect('/');
    }
    res.send(`<h1>Hello, ${req.user.displayName}</h1><a href="/logout">Logout</a>`);
});

// Logout Route
app.get('/logout', (req, res, next) => {
    req.logout((err) => {
        if (err) return next(err);
        res.redirect('/');
    });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Conclusion

By combining Express, Passport.js, and the Google OAuth 2.0 strategy, developers can implement robust, secure, and industry-standard third-party authentication flows with minimal overhead.