I have a middle wear in my Express app that sets a cookie in the clients browser:
res.cookie('token', '123');
Everything works perfect on a local environment with the front end calling local the server:
axios
.post(`http://localhost:3000/createSomething`, { 'field': "value"})
.then(res => {
console.log('res', res)
})
.catch(err => {
return Promise.reject(
new Error('There is an issue with the /createSomething endpoint')
);
});
In this situation the cookie gets set and I can see it in my dev tools under the Cookies section. The issue is when I change my front end call to point to the AWS Elastic Beanstalk environment:
http://localhost:3000/createSomething -> https://testEnvironment.com/createSomething
The call is successful but no cookie is created in the clients browser. Although, In the response headers I do see:
set-cookie: paigetoken=123; Path=/
A few further details:
How can I resolve this issue and have my Express app in AWS ELB environment successfully set a cookie in the clients browser? Any insight would be greatly appreciated!
Since I'm not totally sure how your environment is set up, the issue may be that the client is requesting information from localhost
meaning that it would be requesting data from the clients same machine. Try changing your URL in the client code to:
`${location.origin}/createSomething`
This presents a security issue in most browsers. Imagine a malicious site overriding a login token cookie for lets say Google. In order for a server to set the cookie, location.origin
must match in both the client and the requested endpoint.
A work around you could use is have the server send a response telling the client to set the cookie on the front-end.
For example: on the server you could do something like this to send a header with the cookie information.
res.set('X-SetCookie', JSON.stringify({ name: "token", value: "123" }));
Then in the client, something like this to actually set the cookie.
axios
.post(`http://localhost:3000/createSomething`, { 'field': "value"})
.then(res => {
// Set cookie function.
function setCookie({ name, value, expires = 1000*60*60*24*365 }) {
const time = new Date();
time.setTime(time.getTime() + expires);
document.cookie = `${name}=${value};expires=${time.toUTCString()};path=/`;
}
// If response has the X-SetCookie header, set the cookie client side.
if(res.headers.hasOwnProperty("X-SetCookie")) setCookie(JSON.parse(res.headers["X-SetCookie"]));
console.log('res', res)
})
Just make sure you configure CORS properly so the browser can see the header: Axios get access to response header fields