The Hydrogen framework includes built-in support for session management. This guide provides an introduction to how sessions work in your Hydrogen app.
What's a session?Anchor link to section titled "What's a session?"
A session is a set of user interactions that take place within a given timeframe. Each session tracks the global data that's unique to each user.
For example, session data might contain the products within a cart, site preferences, and user identity. Session data persists across page refreshes, but it eventually expires, depending on how it's configured.
Configuring sessionsAnchor link to section titled "Configuring sessions"
The Demo Store template comes pre-configured with session support.
By default, session data is persisted within a cookie. You can adjust the session cookie configuration within
App.server.jsx for an in-memory storage or file-based storage (NodeJS only), or build your own storage adapter.
Types of session storageAnchor link to section titled "Types of session storage"
The following table describes the types of session storage available by default in Hydrogen:
|Cookie session storage||CookieSessionStorage||The default session storage mechanism for Hydrogen. Cookies are convenient because you don't need a database or another backend service to persist the data.|
|In-memory session storage||MemorySessionStorage||Stores the session data within Hydrogen runtime memory. You still need to configure cookies because a unique session ID is stored within the browser cookie, even though associated session data is stored in memory.|
|File session storage||FileSessionStorage||Persists session data to the file system. This is useful if you need to store a lot of data in the session (more than the 4kb cookie limit) and also have the data persist when Hydrogen restarts.
Cookie configuration is still necessary because a unique session ID is stored within the browser cookie, although associated session data is stored in the file system.
Custom session storageAnchor link to section titled "Custom session storage"
If you want to persist session data in a custom way, then you can write your own session storage adapter. To do so, you need to implement a function that returns an object:
Reading and updating session dataAnchor link to section titled "Reading and updating session data"
In Hydrogen, you can use the
useSession hook to read session data. You can update session data within API routes. API routes are passed a session object for interacting with the session. The session object has the following keys:
||An async function that resolves with the current session state.|
||An async function to modify a portion of the session state.|
||An async function to destroy the current session.|
The following example shows an API route that's used to retrieve, set, and delete a
countryCode within a session:
The following example shows a server component which reads data from the session: