0

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?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
William Le
  • 825
  • 1
  • 9
  • 16
  • 1
    Clients cannot set `HttpOnly` cookies. "HttpOnly" is to be understood as "as opposed to JavaScript". Only the server can, via a `Set-Cookie` response header, set a `HttpOnly` cookie. – jub0bs Jul 07 '23 at 16:12
  • 1
    Does this answer your question? [Set a cookie to HttpOnly via Javascript](https://stackoverflow.com/questions/14691654/set-a-cookie-to-httponly-via-javascript) – Heretic Monkey Jul 07 '23 at 19:24
  • @HereticMonkey very insightful! – William Le Jul 08 '23 at 02:44

1 Answers1

1

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.

jub0bs
  • 60,866
  • 25
  • 183
  • 186