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:

fetch("") .then(response => response.json()) .then(data => console.log(data));

This will make a request to the server at 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.

fetch("", { 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.

fetch("", { 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.

const instance = axios.create({ withCredentials: true }); instance.get("") .then(response => console.log(;

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

axios.get("", { withCredentials: true }) .then(response => console.log(;

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:

axios.defaults.withCredentials = true; axios.get("") .then(response => console.log(;


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 All rights reserved. Made with ❤ in NY.