Cookies don't transfered in react and express.js

江枫思渺然 提交于 2020-01-16 08:46:54

问题


I have been working on project which backend uses express and apollo server and front end uses react js. Locally everything seems fine as server runs on port 2000 and react js runs on 3000. After building my react app I copied everything and place them server's public folder but after uploading them to remote server users can't authenticate since session id is not get transferred.

Here is how I have configured base url in react app.

App.js

let BASE_URL = ''
let WS_BASE_URL = ''
let credentials = '';

if (process.env.NODE_ENV === 'production') {
    BASE_URL = 'https://example.com/graphql'
    WS_BASE_URL = 'wss://example.com/graphql'
} else {
    BASE_URL = 'http://localhost:2000/graphql'
    WS_BASE_URL = 'ws://localhost:2000/graphql'
    credentials = 'include'
}

// Create an http link:
const httpLink = new HttpLink({
    uri: BASE_URL,
    credentials,
})

// Create a WebSocket link:
const wsLink = new WebSocketLink({
    uri: WS_BASE_URL,
    options: {
        reconnect: true,
    },
})

and this is how I configured cors and session in server

server.ts

    const app = express();

    app.use(cors({
        credentials: process.env.NODE_ENV !== "production",
        origin: ['http://localhost:3000'] //React app.
    }));

    app.use(session({
        store,
        name: COOKIE_NAME,
        secret: config.get('session_secret'),
        resave: false,
        saveUninitialized: false,
        cookie: {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            maxAge: 1000 * 60 * 60 * 24 * 30 // 1 month
        }
    }));

When locally i can see session id when I inspect network requests but in production it is not there. I believe I am missing something in this configuration and don't even know what is it. Any help will be appreciated.

来源:https://stackoverflow.com/questions/59224406/cookies-dont-transfered-in-react-and-express-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!