R__T R__T - 1 year ago 66
Node.js Question

Redirect to a URL fragment resets session on Chrome (Node/React/React-Router)

I have an app that is using node on the backend and react (with a hash history) on the front end.

This means my api endpoint URLs look like:


and my react endpoints are all fragments from the root:


After logging the user in (through OAuth2) I want to redirect the user to a specific URL fragment within the React SPA.

My first thought for doing this was to just have the server redirect me to the URL fragment.

My route handler looks something like:

app.get('/oauthCallback', (req, res) => {
req.session.token = 'some token'

In Safari this works fine and any further API requests made from the SPA have share the same req.session and therefore have the token and can make authenticated downstream requests.

However, in Chrome, upon redirection the next API request causes the creation of a new session, thus losing the token and preventing authenticated requests from succeeding.

Everything works fine when redirect to another api endpoint (not in the SPA).

It also does not work if I redirect to
, the root of the SPA.

I'm wondering if there is something I don't know about how chrome handles URL fragments and sessions.


So after 3 days of misery I've worked this out.

Turns out it is not Chrome that is exhibiting incorrect behaviour, but Safari.

The library I am using for making XHR requests does not send cookies to the server with the client request unless you include the option: credentials: 'same-origin.

For example:

fetch(endpoint, { method, headers, credentials: 'same-origin' })
    .then(res => {
        // do something

Looks like safari is sending them anyway, which is what causes the confusion. Hopefully this will help someone.