If you have an example of code from any of your projects for nextjs using passport google oauth2, please share. There are some examples online for this using just nodejs but the mechanism of routes, middleware and callback is different with nextjs and I have not found a working example.
I have the following code but get a CORS error. I have seen youtube videos with google auth demos on localhost. The credentials I created also use localhost.
\lib\Passport.js
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((req, id, done) => {
req.db
.collection('users')
.findOne({ _id: id })
.then((user) => done(null, user));
});
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: process.env.WEB_URI+"/users/callback/google",
passReqToCallback: true,
},
function(accessToken, refreshToken, profile, cb) {
// User.findOrCreate({ googleId: profile.id }, function (err, user) {
// return cb(err, user);
// });
console.log("profile below")
console.log(profile)
}
));
export default passport;
\pages\login.js with button - "Login using Google"
<Button
variant="outlined"
color="secondary"
startIcon={">"}
onClick={(event) => {
googleLogin(event) }}
>
Login using Google
</Button>
and the function in \pages\login.js
async function googleLogin(e) {
const res = await fetch('/api/authGoogle', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
})
console.log(res);
return;
}
And the \pages\api\authGoogle.js
import nextConnect from 'next-connect';
import middleware from '../../middlewares/middleware';
import passport from '../../lib/passport';
const handler = nextConnect();
handler.use(middleware);
handler.get(passport.authenticate("google", {
scope: ['profile', 'email', 'openid'],
}))
handler.delete((req, res) => {
req.logOut();
res.status(204).end();
});
export default handler;
What I do not have is code for users/callback/google and I am not sure what to write in it. The official passportjs example used just nodejs and hard to follow so any sample using next js will help me and others in future.