(Node.js, Passport, Google OAuth) After google oauth login with Passport.js, subsequent api request doesn't send cookie along (only deployment)

PLEASE help us help you by writing a good post!

  • we need to know your netlify site name. Example: gifted-antelope-58b104.netlify.app
  • DNS issues? Tell us the custom domain, tell us the error message! We can’t help if we don’t know your domain.
  • Build problems? Link or paste the FULL build log & build settings screenshot

The better the post - the faster the answer.

Hi team,

I have deployed an app through netlify : https://my-recipe-note-app.netlify.app/

I have attached google oauth login and it seems I have successfully receive set-cookie header and cookie set after google callback api.
However, after receiving cookies, subsequent api request (api/current_user) has to send along cookie toward backend but it is omitting cookie. On localhost it works fine but after frontend deployment it doesn’t work.
When I send request directly toward backend, it also works fine so I guess it is problem from client side after deployment.

here is my frontend repository(public) GitHub - YeonhaPark/my-recipe-note-front: frontend for my recipe note project

here is my backend cookie setup source code

app-route.js

import express from 'express';
import cors from 'cors';
import cookieSession from 'cookie-session';
import passport from 'passport';
import morgan from 'morgan'; // 사용자에게 받은 요청에 대해 매번 console해줄 필요 없이 자동으로 로그 생성 https://github.com/expressjs/morgan
import helmet from 'helmet'; // 공통적으로 보안에 필요한 헤더들을 추가해줌
import 'express-async-errors';
import postRouter from './router/post.js';
import tagRouter from './router/tag.js';
import authRouter from './router/auth.js';
import { config } from './config.js';
import db from './models/index.js';
import './services/passport.js';

const app = express();
const whitelist = [
  'http://localhost:3000',
  'https://my-recipe-note-app.netlify.app',
];

const corsOptions = {
  origin: whitelist,
  credentials: true,
  sameSite: 'none',
  secure: true,
  methods: 'GET,PUT,POST,DELETE,UPDATE,OPTIONS',
  allowedHeaders:
    'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept',
};

app.use(cors(corsOptions));
app.set('trust proxy', 1);
app.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000, // how long this cookie could exist in browser
    keys: [config.auth.cookieKey],
  })
);

app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.use(morgan('combined'));
app.use(express.urlencoded({ extended: false }));
app.use(helmet());

app.use('/', authRouter);
app.use('/recipes', postRouter);
app.use('/tags', tagRouter);

app.use((req, res, next) => {
  res.sendStatus(404);
});

app.use((err, req, res, next) => {
  console.error(err);
  res.sendStatus(500);
});
db.sequelize.sync().then(() => {
  console.log(`Server started...${new Date()}`);
  app.listen(config.port);
});

router/auth.js

import passport from 'passport';
import express from 'express';

const router = express.Router();

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

router.get(
  '/auth/google/callback',
  passport.authenticate('google', {
    successRedirect: `${process.env.CORS_ALLOW_ORIGIN}/main`,
    failureRedirect: `${process.env.CORS_ALLOW_ORIGIN}/login`,
  })
);

router.get('/api/logout', (req, res) => {
  req.logout();
  res.send(req.user);
});

router.get('/api/current_user', (req, res) => {
  res.send(req.user);
});

export default router;

passport.js

import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
import { config } from '../config.js';
import db from '../models/index.js';

const { User } = db;
const { auth } = config;
const { googleClientId, googleClientSecret } = auth;

passport.serializeUser((user, done) => {
  console.log('serialize user called', user);
  return done(null, user.id);
});

// turn id into user model instance
passport.deserializeUser((id, done) => {
  console.log('deserialize user calleld');
  User.findOne({ where: { id } }).then((user) => {
    return done(null, user);
  });
});

passport.use(
  new GoogleStrategy(
    {
      clientID: googleClientId,
      clientSecret: googleClientSecret,
      callbackURL: '/auth/google/callback',
      proxy: true,
    },
    (accessToken, refreshToken, profile, done) => {
      User.findOne({ where: { googleId: profile.id } }).then((existingUser) => {
        if (existingUser) {
          console.log('existing user', existingUser);
          done(null, existingUser);
        } else {
          // make a new record
          console.log('new user');
          new User({ googleId: profile.id })
            .save()
            .then((user) => done(null, user));
        }
      });
    }
  )
);

I also have set netlify related files but it doesn’t work
__redirects

/api/* https://my-recipe-note-back.herokuapp.com/:splat 200

Is it something related with netlify settings ? What would be the reason that blocks the cookie?

Hey there, @YeonhaPark :wave:

Thanks for your patience, and welcome to the Netlify Forums! I want to assure you we have not forgotten about your question. For transparency, I have looped in the relevant team at Netlify and a member of Support will follow up once we have some next steps for you.

Thanks :netlisparkles:

Hey @YeonhaPark,

Sorry for the delay here. Is there a test account that we can have to test this?

Any information about this? How did you solve it?

Hey there, @watthecode :wave:

Welcome to the Forums. Sorry you are having trouble with your build.

This Support Guide contains a ton of useful debugging tips that can likely help you solve your problem :slight_smile: Additionally, this Support Guide houses all of our resources for debugging build and deploy issues.

We also recommend trying to search the forums with the build error you encountered - it’s likely your question was already asked by someone else!

If you are still having problems, please provide as much information as you can on what you have already tried, what your build settings are, your package.json, etc. Thanks!