Search code examples
reactjscookieshttponly

Cannot send httponly cookie using fetch


I'm trying to send HttpOnly cookie from React frontend to NodeJS backend. I have checked that if the cookie is not HttpOnly, everything works as expected, but if not then the server does not receive any cookies.

import Cookies from 'universal-cookie';

const cookies = new Cookies();

cookies.set(
  'refreshToken',
  'refreshToken',
  { 
    path: '/', 
    httpOnly: false, // this works
    // httpOnly: true, // this does not
    maxAge: 365 * 24 * 60 * 60 * 1000, 
  }
);

const response = await fetch('http://localhost:4000/api/auth/refresh', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  credentials: 'include', // should enable sending HttpOnly cookie?
});

I tried setting domain as localhost but nothing changed. How should I fix this?


Solution

  • Clients (i.e. some script in React) cannot set HttpOnly cookies. Only the server can, via a Set-Cookie response header, set a HttpOnly cookie. See the relevant passage of the IETF draft entitled Cookies: HTTP State Management Mechanism:

    The HttpOnly attribute limits the scope of the cookie to HTTP requests. In particular, the attribute instructs the user agent to omit the cookie when providing access to cookies via non-HTTP APIs.