Search code examples
node.jsgoogle-app-engineexpress-session

use express-session secure in app deployed to google app engine


I have a Next app that communicates with my node.js server.

In dev mode, everything works fine even when deployed to Google, but when I change the environment, this is where the problem begins.

Basically, I have this express-session setup:

if(process.env.NODE_ENV !== 'development'){
    app.set('trust proxy', 1);
}

app.use(
    session(
        { 
            //store: redisStore,
            secret: process.env.SERVER_SESSION_SECRET,
            resave: false,
            saveUninitialized: false,
            cookie: {
                maxAge: 14 * 24 * 60 * 60 * 1000, 
                httpOnly: process.env.NODE_ENV === 'development' ? false : true,
                secure: process.env.NODE_ENV === 'development' ? false : true, 
                sameSite: process.env.NODE_ENV === 'development' ? false : 'none', 
                domain: process.env.BASE_URL || 'localhost',
                proxy: true,
            }
        }
    )
);

When I fetch the API, this should set a cookie, but it's not doing that. I know the problem may be related to HTTP and HTTPS, but my URL is already HTTPS (I just added my custom domain). Do I need to configure something else in GAE?

Don't know if this is helpful but my app.yaml looks like this:

env: standard
runtime: nodejs18
service: stg
handlers:
- url: /.*
  script: auto
  secure: always

Solution

  • Posting my previous comment as an answer.

    The issue was resolved by adding the following code inside the js file:

    app.set('trust proxy', true);
    

    Also, make sure that env variables are correct.

    You can check this documentation on HTTPS and forwarding proxies which contains the trust proxy setting for Express.js.