Set-cookie isn't working with React and Django

I am trying to make a simple session-based authentication with Django and React, but the browser won't set cookies

LoginView:

class LoginView(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return Response(
                {"message": "Login successful", "username": user.username},
                status=status.HTTP_200_OK,
            )
        else:
            return Response(
                {"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED
            )

Front-end logic:

  const getData = () => {
    fetch("http://127.0.0.1:8000/me/").then(
      (res) => {
        return res.json()
      }
    ).then(
      (data) => {
        setUsername(data.username)
      }
    )
  }

  const login = () => {
    fetch("http://127.0.0.1:8000/login", {
      method: "POST",
      body: JSON.stringify({
        "username": "user",
        "password": "password"
      }),
      headers: {
        "Content-Type": "application/json",
      }
    }).then(function(response){
      return response.json();
    }).then((data) => console.log(data));
    getData()
  }

Note: Backend actually sends back Set-Cookie header:

set-cookie:
csrftoken=OHi2iTT8vDvnn7pAzbb705zrj3gFkFLK; expires=Thu, 15 Jan 2026 08:31:49 GMT; Max-Age=31449600; Path=/
set-cookie:
sessionid=jna0kbgo4k8x8spoyzyyxch2d24bz2li; expires=Thu, 30 Jan 2025 08:31:49 GMT; HttpOnly; Max-Age=1209600; Path=/

The Window API by default does not include cookies for fetch(…) [mdn-doc]. You can use credentials: true [mdn-doc] as option to enable sending cookies:

const getData = () => {
    fetch("http://127.0.0.1:8000/me/", {credentials: true})
}
Вернуться на верх