Skip to content
Advertisement

Make Axios send cookies in its requests automatically

I am sending requests from the client to my Express.js server using Axios.

I set a cookie on the client and I want to read that cookie from all Axios requests without adding them manually to request by hand.

This is my clientside request example:

JavaScript

I tried to access headers or cookies by using these properties in my Express.js server:

JavaScript

Neither of them contained any cookies. I am using cookie parser middleware:

JavaScript

How do I make Axios send cookies in requests automatically?

Edit:

I set cookie on the client like this:

JavaScript

While it’s also using Axios, it is not relevant to the question. I simply want to embed cookies into all my requests once a cookie is set.

Advertisement

Answer

You can use withCredentials property.

XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request.

JavaScript

Also its possible to force credentials to every Axios requests

JavaScript

Or using credentials for some of the Axios requests as the following code

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement