fetch: Getting cookies from fetch response
The problem turned out to be with the fetch option credentials: same-origin/include
not being set.As the fetch documentation mentions this option to be required for sending cookies on the request, it failed to mention this when reading a cookie.
So I just changed my code to be like this:
fetch('/login/local', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, credentials: 'same-origin', body: JSON.stringify({ username: this.state.username, password: this.state.password, }), }).then(res => { return res.json(); }).then(json => { if (json.success) { this.setState({ error: '' }); this.context.router.push(json.redirect); } else { this.setState({ error: json.error }); } });
From Differences from jQuery section of https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
- fetch() won't receive cross-site cookies. You can’t establish a crosssite session using fetch(). Set-Cookie headers from other sites aresilently ignored.
- fetch() won’t send cookies, unless you set thecredentials init option. Since Aug 25, 2017: The spec changed thedefault credentials policy to same-origin. Firefox changed since61.0b13.)