How to Pass Cookies with Fetch or Axios Requests

Updated onbyAlan Morel
How to Pass Cookies with Fetch or Axios Requests

Cookies are a critical part of the web as they are used to store information about the user to help customize the experience.

However, cookies are not sent by default when you make client-side requests to the server.

In this post, we're going to learn how to pass cookies to the server when we make requests using the native fetch API or the popular axios library.

Passing cookies with fetch

The fetch API is a great improvement over the original XMLHttpRequest API, as it makes requests easier to work with and provides a lot of functionality.

Let's look at an example fetch request:

JAVASCRIPT
fetch("http://example.com/data.json") .then(response => response.json()) .then(data => console.log(data));

This will make a request to the server at http://example.com/data.json and return the response as a JSON object, then log the data to the console.

If you want to pass cookies with this request, you can do so by passing the credentials option to the fetch request.

JAVASCRIPT
fetch("http://example.com/data.json", { credentials: "same-origin" }) .then(response => response.json()) .then(data => console.log(data));

You can also try the value of include in the credentials property of the request object.

JAVASCRIPT
fetch("http://example.com/data.json", { credentials: "include" }) .then(response => response.json()) .then(data => console.log(data));

Either way, with this enabled, you should see cookies being sent over.

Passing cookies with axios

Axios is a popular library for making HTTP requests because the API is simple yet powerful.

With axios, you can first create a new instance of axios while enabling cookies to be sent.

From there, any requests made with this instance will automatically send cookies.

JAVASCRIPT
const instance = axios.create({ withCredentials: true }); instance.get("http://example.com/data.json") .then(response => console.log(response.data));

If you don't want to set it for the entire instance, you can set it on a per-request basis.

JAVASCRIPT
axios.get("http://example.com/data.json", { withCredentials: true }) .then(response => console.log(response.data));

Finally, axios even gives you the ability to set cookies automatically globally. This is useful in situations where you're sure you want cookies in every request.

Here's how to set cookies globally:

JAVASCRIPT
axios.defaults.withCredentials = true; axios.get("http://example.com/data.json") .then(response => console.log(response.data));

Conclusion

In this post, we looked at how to pass cookies with fetch and how to pass cookies with axios.

These are the two most popular ways to send requests so hopefully this works for your project.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.