# CSRF Cookie is not set with react frontend

**URL:** <https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509>\
**Category:** Templates & Frontend\
**Created:** [February 9, 2021, 6:46pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509 "2021-02-09T18:46:16Z")\
**Posts on this page:** 17\
**Page:** 2

<div class="post-metadata">

**Author:** ![Bharath3697](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bharath3697/32/3439_2.png) [@Bharath3697](https://forum.djangoproject.com/u/Bharath3697)\
**Post date:** [February 10, 2021, 3:43pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/21 "2021-02-10T15:43:53Z")

</div>

But no where in the django documents it is mentioned to send the csrftoken as separate cookie rather than sending it in header by the name X-CSRFToken. If you could show me a sample request on how it is supposed to be sent, it would be helpful.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 10, 2021, 4:05pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/22 "2021-02-10T16:05:36Z")

</div>

I don’t have any information to provide other than what’s documented in the [CSRF Protection docs](https://docs.djangoproject.com/en/3.1/ref/csrf/#ajax). I’ve never had any problems with it, it has always “just worked” for me.

Looking back at your first post, I don’t see where you’ve set the [CSRF\_HEADER\_NAME](https://docs.djangoproject.com/en/3.1/ref/settings/#csrf-header-name) setting. (Also see the [AJAX paragraph](https://docs.djangoproject.com/en/3.1/ref/csrf/#ajax) in the CSRF Protection docs.)

---

<div class="post-metadata">

**Author:** ![Bharath3697](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bharath3697/32/3439_2.png) [@Bharath3697](https://forum.djangoproject.com/u/Bharath3697)\
**Post date:** [February 10, 2021, 4:09pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/23 "2021-02-10T16:09:11Z")

</div>

by default [CSRF\_HEADER\_NAME](https://docs.djangoproject.com/en/3.1/ref/settings/#csrf-header-name) name is HTTP\_X\_CSRFTOKEN, which is available in the request Meta, still csrf cookie not set error is thrown

---

<div class="post-metadata">

**Author:** ![Bharath3697](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bharath3697/32/3439_2.png) [@Bharath3697](https://forum.djangoproject.com/u/Bharath3697)\
**Post date:** [February 10, 2021, 4:16pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/24 "2021-02-10T16:16:42Z")

</div>

ken, when i print the request.META i can see the csrf cookie in HTTP\_X\_CSRFTOKEN key. But once i print request.COOKIES it is returning {} empty.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 10, 2021, 4:55pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/25 "2021-02-10T16:55:51Z")

</div>

That’s fine - actually good. (The middleware looks for the cookie _before_ looking for the X-CSRFToken header. If a cookie _was_ being supplied, and was an incorrect cookie, that would have been a cause of a problem.)

---

<div class="post-metadata">

**Author:** ![Bharath3697](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bharath3697/32/3439_2.png) [@Bharath3697](https://forum.djangoproject.com/u/Bharath3697)\
**Post date:** [February 10, 2021, 5:13pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/26 "2021-02-10T17:13:51Z")

</div>

I have been reading the middleware and making dummy requests, couldn’t find anything wrong with the middleware or the code i wrote. seems like it might be the issue on the frontend.  
Thanks for your valuable time ken. I really appreciate it. If i get to know what might have caused this issue, i will surely update here

---

<div class="post-metadata">

**Author:** ![YashasKirito](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/yashaskirito/32/6536_2.png) [@YashasKirito](https://forum.djangoproject.com/u/YashasKirito)\
**Post date:** [December 3, 2021, 2:23pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/27 "2021-12-03T14:23:05Z")

</div>

Hello @Bharath3697, I have been facing the same issue you had been facing and I managed to fix it. No, it’s not a frontend issue. You just need to add a few configurations in your settings.py of your Django App.

You just need to add `CSRF_TRUSTED_ORIGINS` where you specify your web app URL

```auto
CSRF_TRUSTED_ORIGINS = [
     "example.com"
]

```

This might be helpful for anyone who is struggling with this (I know the pain)

If you still face the same error try it with this config also:

```auto
SESSION_COOKIE_SAMESITE = None

```

---

<div class="post-metadata">

**Author:** ![PRA1995SAG](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pra1995sag/32/2207_2.png) [@PRA1995SAG](https://forum.djangoproject.com/u/PRA1995SAG)\
**Post date:** [December 6, 2021, 3:50am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/28 "2021-12-06T03:50:46Z")

</div>

@KenWhitesell , @Bharath3697 , hope you’re doing well and staying safe! 😷

> Environment

- Django==3.1.1
- django-cors-headers==3.10.0
- frontend - React.js

> Issue

- trying to submit a form (used to create new user) (`POST`), gives 403

- front-end is `React.js` so there will is no `{% csrf_token %}` in the form

- form used to create new user

- although, now I know that session is server-side thing and we store those in browser in the form of cookies

- I’m no longer returning HTTP response from any of the views, because frontend is React.js for this project

- I’ve managed `CORS`

> CORS\_ALLOW\_ALL\_ORIGINS = True

- question

1. how/where\_from to get the csrf\_token for that particular view function and the request and return it in `JsonResponse` ?
2. How could the client can successfully complete the form request ?

- register page is the first page when client visits server
- how could client set csrf there ? (in request)

> views.py

```python
@ensure_csrf_cookie
def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        try:
            user = User.objects.create_user(username, email, password)
            user.save()
            return JsonResponse({"message":"User Registered."})

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [December 6, 2021, 5:13am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/29 "2021-12-06T05:13:44Z")

</div>

Start with the [AJAX docs](https://docs.djangoproject.com/en/3.2/ref/csrf/#ajax) in the [CSRF page](https://docs.djangoproject.com/en/3.2/ref/csrf/). That has always covered it for me. (Caveat: I’ve never used React.)

---

<div class="post-metadata">

**Author:** ![mboekhold](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mboekhold/32/5743_2.png) [@mboekhold](https://forum.djangoproject.com/u/mboekhold)\
**Post date:** [December 23, 2021, 9:38am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/30 "2021-12-23T09:38:31Z")

</div>

Hi @Bharath3697 did you find a solution?

---

<div class="post-metadata">

**Author:** ![Bharath3697](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/bharath3697/32/3439_2.png) [@Bharath3697](https://forum.djangoproject.com/u/Bharath3697)\
**Post date:** [December 27, 2021, 6:54pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/31 "2021-12-27T18:54:32Z")

</div>

Nope. I shifted to token based authentication

---

<div class="post-metadata">

**Author:** ![onuriltan](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/onuriltan/32/11011_2.png) [@onuriltan](https://forum.djangoproject.com/u/onuriltan)\
**Post date:** [November 23, 2022, 10:10am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/32 "2022-11-23T10:10:51Z")

</div>

I don’t know if it will apply to your case but for mine there was no initial path for django project, there was only /api route, that result in browser to not set the cookie. After I added initial hello world get path to base path e.g

GET [http://localhost:8080](http://localhost:8080) Respose: Hello World

browser started to set the cookie

---

<div class="post-metadata">

**Author:** ![mozilla01](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/mozilla01/32/14855_2.png) [@mozilla01](https://forum.djangoproject.com/u/mozilla01)\
**Post date:** [July 19, 2023, 8:32am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/33 "2023-07-19T08:32:50Z")

</div>

Hello.

I had run into the same problem. My session cookies from my Django API were not getting set on my React frontend since they were communicating in a cross site context. The solution was to tweak these settings on the backend:

1. Allow for the cookies to be sent

```auto
CORS_ALLOW_CREDENTIALS = True

```

1. Adding the frontend server to `CSRF_TRUSTED_ORIGINS`

```auto
CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:5173"]

```

1. Changing `SESSION_COOKIE_SAMESITE` from `Lax` to `None`

```auto
SESSION_COOKIE_SAMESITE = None

```

For this setting, it is essential to take the below step.

1. Changing `CSRF_COOKIE_SECURE` from `False` to `True`

```auto
CSRF_COOKIE_SECURE = True

```

Note: For the above setting, you need to be using an `HTTPS` protocol or your `localhost`.

I have enlisted the above settings assuming you have added the basic configuration for the `django-cors-headers` package to your settings.

Reference: I normally test in FIrefox, but decided to test in Chrome for once. When the cookies were being sent, Chrome gave a detailed explanation about why the cookies could not be set. I referred MDN for some more clarity.

> **[Set-Cookie - HTTP | MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie)**
>
> The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later.
> To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.

---

<div class="post-metadata">

**Author:** ![tamusandesh99](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tamusandesh99/32/15078_2.png) [@tamusandesh99](https://forum.djangoproject.com/u/tamusandesh99)\
**Post date:** [July 31, 2023, 1:57am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/34 "2023-07-31T01:57:46Z")

</div>

please tell me someone managed to fix this. This is my settings

```auto
CORS_ALLOWED_ORIGINS = [
    'http://localhost:3000',
    'https://localhost:3000',
    'http://127.0.0.1:3000',
    'http://0.0.0.0',
]
CSRF_TRUSTED_ORIGINS = ['http://localhost:3000',
                        'https://localhost:3000',
                        'http://127.0.0.1:3000',
                        'https://127.0.0.1:3000',
                        'http://0.0.0.0']

CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False

```

The cookie is sent from backend. If I go to api/getcsrfcookie url in normal browser, I can see the cookie value in the storage part of dev tools but with react, I am doing the same thing. I am doing axios.get(api/getcsrfcookie) in one component then rendering that component to another component but there is no cookie in storage. I can see the set-cookie in network tab in dev tools. I am about to lose my mind. It was working before but I cleared cache is it stopped working

---

<div class="post-metadata">

**Author:** ![tamusandesh99](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tamusandesh99/32/15078_2.png) [@tamusandesh99](https://forum.djangoproject.com/u/tamusandesh99)\
**Post date:** [August 2, 2023, 9:42pm UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/35 "2023-08-02T21:42:21Z")

</div>

For future people, in my case with react, I added withcredentials: true when sending a request and it fixed my problem. My code is like this

```auto
const config = {
    withCredentials: true,
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRFToken": Cookies.get('csrftoken')
    },
  };

  const body = JSON.stringify({ username, password, email });

  try {
    const res = await axios.post(
      `${process.env.REACT_APP_API_URL}/user/register`,
      body,
      config,
    );

```

---

<div class="post-metadata">

**Author:** ![nate-hunter](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nate-hunter/32/17647_2.png) [@nate-hunter](https://forum.djangoproject.com/u/nate-hunter)\
**Post date:** [December 8, 2023, 7:18am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/36 "2023-12-08T07:18:49Z")

</div>

Also, just to add to @tamusandesh99 's answer, for those using `fetch`, use `{ credentials: 'include' }`, e.g.:

```javascript
const response = await fetch(CSRF_URL, {
    credentials: 'include',
});
const cookie = await response.headers.get('X-CSRFToken');
setCsrfToken(cookie);

```

Also, with some help from [this blog](https://testdriven.io/blog/django-spa-auth/) (and Django docs + SO), here are my related settings:

```python
# -------- CROSS DOMAIN SESSION AUTHENTICATION
# CSRF_COOKIE_HTTPONLY = True
CSRF_TRUSTED_ORIGINS = [
    'http://localhost:5173',
    'http://127.0.0.1:5173',
]
CSRF_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_HTTPONLY = True

# PROD SETTINGS
# CSRF_COOKIE_SECURE = True
# SESSION_COOKIE_SECURE = True

CORS_ALLOWED_ORIGINS = [
    'http://localhost:5173',
    'http://127.0.0.1:5173',
]
CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken']
CORS_ALLOW_CREDENTIALS = True

```

…commenting out `CSRF_COOKIE_HTTPONLY = True` allows me to access the cookie in React. I know the docs mention that setting this to True “offers little practical benefit”, but I’m curious if I should have this set to True since it’s mentioned in the blog? My server + browser are hosted separately, which is a new setup for me so I’m sure I’m missing something… anyways just thinking out loud.

---

<div class="post-metadata">

**Author:** ![tamusandesh99](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tamusandesh99/32/15078_2.png) [@tamusandesh99](https://forum.djangoproject.com/u/tamusandesh99)\
**Post date:** [February 7, 2024, 1:25am UTC](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509/37 "2024-02-07T01:25:14Z")

</div>

For more info towards future people,

if the issue is in prod, where your backend and frontend is hosted by two different servers with different domains then the cookie will not set because of security reasons. For example if you frontend is is [mydomain.com](http://mydomain.com) and backend is in [backend.com](http://backend.com) then it wont work. Both BE and FE needs to be in same domain. If your frontend is in [mydomain.com](http://mydomain.com) then you can add subdomain for backend such as [api.mydomain.com](http://api.mydomain.com) then the browser will accept and store the cookie. Additionally if you haven’t you will need to add these settings:

```auto
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_HTTPONLY = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = True # Set to True in production (requires HTTPS)
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_DOMAIN = '.mydomain.com'

```

[Previous page](https://forum.djangoproject.com/t/csrf-cookie-is-not-set-with-react-frontend/6509.md?page=1)
