Skip to main content

Cookie

The Cookie component helps you build your own custom cookie and session implementations. All Hydrogen session storage mechanisms use the same configuration options as Cookie.

Example code

custom.js
import {Cookie} from '@shopify/hydrogen';
let cookie = new Cookie('__session', {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 60 * 60 * 24 * 30,
});
cookie.parse(request.headers.get('cookie'));
cookie.set('new', 'data');
response.headers.set('Set-Cookie', cookie.serialize());

The following table describes the options for how the cookie is persisted within the browser. The properties are derived from the cookie specification:

OptionTypeDescription
expiresdateA date on which the cookie will expire. If the date is in the past, then the browser will remove the cookie.
maxAgenumberThe number of seconds until the cookie expires. maxAge takes precedence over expires if both are defined.
securebooleanWhether to secure the cookie so that the browser only sends the cookie over HTTPS. Some browsers don't work with secure cookies on localhost.
httpOnlybooleanWhether to secure the cookie so that client-side JavaScript can't read the cookie.
sameSite"lax" | "strict" | "none"Declares that the cookie should be restricted to a first-party or same-site context.
pathstringTells the browser that the cookie should only be sent to the server if it's within the defined path.
domainstringSecures the cookie so that it's only used on specific domains.

Component type

The Cookie component is a server component. For more information about component types, refer to React Server Components.