Open learnyx-ai opened 1 year ago
The issue is likely occurring because you are calling res.redirect() directly within the Passport authenticate callback function. This will cause headers to be sent twice - once from the redirect and once from the original request handler.
A few ways to fix:
this.passportService.authenticate(
EnabledAuthenticationStrategies.GOOGLE,
{
failureRedirect: "/login",
successReturnToOrRedirect: `${CURRENT_CLIENT_HOST_URL}/auth/google/success`,
},
(error, user, info) => {
// Remove res.redirect()
done(error, user, info);
}
)(req, res, next);
Then in your request handler:
if(req.user) {
// User authenticated, redirect
res.redirect(`${CURRENT_CLIENT_HOST_URL}/auth/google/success`);
} else {
// Auth failed, handle error
}
this.passportService.authenticate(
EnabledAuthenticationStrategies.GOOGLE,
{
failureRedirect: "/login",
successRedirect: `${CURRENT_CLIENT_HOST_URL}/auth/google/success`,
}
)(req, res, next);
this.passportService.authenticate(
EnabledAuthenticationStrategies.GOOGLE,
(error, user, info) => {
return next();
}
)(req, res, next);
Then handle the redirect there if needed.
Let me know if any of those suggestions help resolve it!
Issue: ERR_HTTP_HEADERS_SENT Error in Passport Google OAuth 2.0 Authentication
Expected behavior
Upon successful authentication using Google OAuth 2.0 with Passport, I expect the user to be redirected to a successful login route.
Actual behavior
I'm getting the
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
when trying to redirect after successful authentication using Google OAuth 2.0 with Passport. The error seems to originate fromresponse.redirect
within thehandleAuthenticationWithGoogleSuccess
function.Steps to reproduce
Here are the main snippets from my code that relate to this issue:
Passport Service
Google Strategy
Controller
server.ts
Environment
I'm unable to pinpoint the reason why this error occurs. I'm looking for any advice on how to troubleshoot or fix this issue. Thanks for any help or suggestions!