← Back to all tutorials

Passport Initial Setup

Install and configure Passport.js — set up the authentication middleware that will handle the OAuth handshake and user sessions.

Passport Initial Setup

Passport.js is Node.js authentication middleware that supports 500+ strategies (Google, Facebook, GitHub, Twitter, etc.). It handles the complex OAuth handshake so you do not have to.

Installing Passport

npm install passport passport-google-oauth20
  • passport — the core authentication middleware
  • passport-google-oauth20 — the Google OAuth 2.0 strategy

Creating the Passport Config

// config/passport-setup.js
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(
    new GoogleStrategy({
        // Options for the Google strategy
        clientID: 'YOUR_CLIENT_ID',
        clientSecret: 'YOUR_CLIENT_SECRET',
        callbackURL: '/auth/google/redirect'
    }, function(accessToken, refreshToken, profile, done) {
        // Passport callback function
        // Called after Google sends back the user profile
        console.log('Passport callback fired');
        console.log(profile);
    })
);

How Passport Works

User hits /auth/google
    ↓
Passport intercepts and redirects to Google
    ↓
User logs in on Google
    ↓
Google redirects to /auth/google/redirect
    ↓
Passport exchanges the code for a token
    ↓
Passport calls your callback with the user profile
    ↓
You decide what to do (save user, create session)

Requiring the Config

// app.js
const passportSetup = require('./config/passport-setup');
// Just requiring it runs the passport.use() code

Key Takeaways

  • Passport is middleware — it sits between the request and your route handler
  • passport-google-oauth20 handles the Google-specific OAuth flow
  • The strategy needs your Client ID, Client Secret, and Callback URL
  • The callback function fires after Google authenticates the user — you receive the profile