React Storefront
|

Cookies

This guide describes how React Storefront handles cookies.

Passing Cookies to API Calls

If you need to forward the cookies sent from the browser when calling an upstream API, you can do so by using fetchWithCookies instead of fetch:

import { fetchWithCookies } from 'fetch'

export default async function myHandler(params, request, response) {
  // this will send all cookies passed by the browser to the API in the cookie header
  const result = await fetchWithCookies('/some/api/endpont').then(res => res.json())

  // ...
}

Note, you should not use fetchWithCookies in routes that are cached. Cookies are unique to the user and a cached response will be seen by multiple users.

React Storefront automatically forwards all Set-Cookie response headers received in fetch calls back to the browser unless the route contains a cache handler with a edge: { maxAgeSeconds } config. React Storefront will never send a set cookie header for a cached route. This is done to maximize caching and prevent multiple users from sharing the same session and/or other personalization.

If you find that you're getting Set-Cookie headers from your upstream API for a mixture of different domains (for example, .domain.com, m.domain.com, and www.domain.com), you can force all cookies onto a single domain using the rewriteCookies function from the react-storefront-extensions/cookies commercial package. You can also ensure that there is at most a single set-cookie header for each combination of name, domain, and path using dedupeCookies(). Simply call these functions at the end of your scripts/moov_response_header_transform.js file:

// scripts/moov_response_header_transform.js
const responseHeaderTransform = require('react-storefront-moov-xdn/responseHeaderTransform').default
const { rewriteCookies, dedupeCookies } = require('react-storefront-extensions/cookies')

module.exports = function() {
  responseHeaderTransform()
  rewriteCookies('.domain.com') // your domain here
  dedupeCookies()
}