I am very new to backend so forgive me if this sounds really basic but I am trying to use passport-google-oauth20 to let users log in through Google and then pass the user information to the ‘/’ route.
This is the part of my passport.js file:
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID!,
clientSecret: process.env.CLIENT_SECRET!,
callbackURL: process.env.CALLBACK_URL,
},
async (accessToken, refreshToken, profile, done) => {
// Get the user data from Google
const newUser = {
googleId: profile.id,
displayName: profile.displayName,
};
try {
// Check if the user exists in the database
let user = await User.findOne({ googleId: profile.id });
if (user) {
done(null, user);
} else {
// Add the user to the database
user = await User.create(newUser);
done(null, user);
}
} catch (err) {
console.error(err);
}
},
),
);
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(async function (id, done) {
const user = await User.findById(id);
done(null, user);
});
Deserializing works great cause I checked and it returns the user info, but when the user gets redirected after a successful callback I can’t access req.user in any of the routes.
Those are my routes:
// Google auth
authRouter.get(
'/auth/google',
passport.authenticate('google', { scope: ['profile'] }),
);
authRouter.get(
'/auth/google/callback',
passport.authenticate('google', {
failureRedirect: process.env.CLIENT_URL }),
(req: Request, res: Response) => {
// Successful authentication, redirect home
res.redirect(process.env.CLIENT_URL!);
},
);
I made this just to see if req.user would work here but it is undefined.
authRouter.get('/', (req: Request, res: Response) => {
console.log(req.user);
});
I can’t access req.user anywhere outside of the ‘auth/google/callback’ route. What am I doing wrong?
const app = express();
app.use(
cors({
origin: process.env.CLIENT_URL,
methods: 'GET,POST,PUT,DELETE',
credentials: true,
}),
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(
session({
secret: process.env.SECRET!,
resave: false,
saveUninitialized: true,
}),
);
app.use(passport.initialize());
app.use(passport.session());
connectDB();
app.use(authRouter);
Please help, I’ve looked everywhere.