Error: Unknown authentication strategy “google” in Passport.js OAuth Setup

I’m trying to implement Google OAuth in my Node.js application using Passport.js, but I keep getting the following error when accessing the /auth/google route:

Error: Unknown authentication strategy "google"
    at attempt (/path/to/project/node_modules/passport/lib/middleware/authenticate.js:193:39)
    at authenticate (/path/to/project/node_modules/passport/lib/middleware/authenticate.js:379:7)
    ...

I’ve already set up my GoogleStrategy and initialized Passport, but something seems to be missing. Below are the relevant files.

auth.ts (Passport Configuration)

import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import User from "../models/user.model";  // Mongoose User model

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) => {
      try {
        let user = await User.findOne({ googleId: profile.id });
        if (!user) {
          user = await User.create({
            googleId: profile.id,
            email: profile.emails![0].value,
            displayName: profile.displayName,
            profilePic: profile.photos![0].value,
          });
        }
        done(null, user);
      } catch (error) {
        done(error, undefined);
      }
    }
  )
);

passport.serializeUser((user: any, done) => done(null, user._id));
passport.deserializeUser(async (id: string, done) => {
  try {
    const user = await User.findById(id);
    done(null, user);
  } catch (error) {
    done(error, null);
  }
});

export default passport;

app.ts (Main Server File)

import express from "express";
import helmet from "helmet";
import cors from "cors";
import morgan from "morgan";
import dotenv from "dotenv";
import mongoose from "mongoose";
import session from "express-session";
import MongoStore from "connect-mongo";
import passport from "./auth";  // Importing the configured Passport instance
import authRoute from "./routes/auth";  // Auth routes

dotenv.config();
const app = express();

// Middleware
app.use(helmet());
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());

app.use(
  session({
    secret: process.env.SESSION_SECRET!,
    resave: false,
    saveUninitialized: false,
    store: MongoStore.create({ mongoUrl: process.env.MONGODB_URI! }),
    cookie: {
      secure: process.env.NODE_ENV === "production",
      sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
      maxAge: 24 * 60 * 60 * 1000, // 24 hours
    },
  })
);

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

// MongoDB Connection
mongoose
  .connect(process.env.MONGODB_URI!)
  .then(() => console.log("Mongodb connected successfully"))
  .catch((err) => console.error(err));

// Routes
app.use("/auth", authRoute);

const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log(`Server listening on port ${port} http://localhost:${port}`);
});

auth.ts (Router)

import express from "express";
import passport from "../auth";  // Using the same Passport instance

const router = express.Router();

router.get(
  "/google",
  passport.authenticate("google", { scope: ["profile", "email"] })
);

router.get(
  "/google/callback",
  passport.authenticate("google", { failureRedirect: "/login" }),
  (req, res) => {
    res.redirect(`${process.env.CLIENT_URL}/dashboard`);
  }
);

export default router;

Packages Installed:

"dependencies": {
    "connect-mongo": "^5.1.0",
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.21.1",
    "express-session": "^1.18.1",
    "helmet": "^8.0.0",
    "mongoose": "^8.7.3",
    "morgan": "^1.10.0",
    "passport": "^0.7.0",
    "passport-google-oauth20": "^2.0.0",
    "passport-local": "^1.0.0"
  },
  "devDependencies": {
    "@types/cors": "^2.8.17",
    "@types/express": "^5.0.0",
    "@types/express-session": "^1.18.0",
    "@types/morgan": "^1.9.9",
    "@types/node": "^22.8.1",
    "@types/passport": "^1.0.17",
    "@types/passport-google-oauth20": "^2.0.16",
    "nodemon": "^3.1.7",
    "ts-node": "^10.9.2",
    "typescript": "^5.6.3"
  }

I’ve verified that:

  1. Google OAuth strategy is registered before routes are used.
  2. The same passport instance is being used across the app.
  3. All necessary packages are installed.
  4. All my env secrets are correct

I’ve also restarted the server multiple times but the error persists.
Double-checked the environment variables.
Ensured only one instance of passport is being used.
Verified the MongoDB connection and session configuration.

Why am I getting the Unknown authentication strategy “google” error, and how can I fix it?