Skip to main content

createCookieSessionStorage

Creates a SessionStorage object that stores all session data directly in the session cookie itself. This eliminates the need for a server-side database or session store.

Signature

CookieSessionStorageOptions
Configuration options for cookie session storage.
The cookie used to store session data, or options to create one automatically.
string
default:"__session"
The name of the cookie.
string[]
Array of secrets for signing cookies. First secret signs new cookies, all are tried when parsing.
string
Cookie domain.
string
default:"/"
Cookie path.
number
Maximum age in seconds.
boolean
default:"true"
Makes cookie inaccessible to JavaScript.
boolean
Only send cookie over HTTPS.
'lax' | 'strict' | 'none'
default:"lax"
Controls cross-site request behavior.

Returns

object
A session storage object with methods to manage sessions.
function
Parses the Cookie header and returns a Session object.
function
Serializes session data and returns the Set-Cookie header. Throws an error if the cookie exceeds 4KB.
function
Returns a Set-Cookie header that clears the session cookie.

Basic Example

filename=app/sessions.server.ts

Login Example

Set session data after authentication:
filename=app/routes/login.tsx

Reading Session Data

Access session data in loaders:
filename=app/routes/dashboard.tsx

Flash Messages

Store temporary messages that are automatically removed after being read:
filename=app/routes/settings.tsx

Logout Example

Destroy the session on logout:
filename=app/routes/logout.tsx

Custom Session Expiration

Set expiration when committing the session:

TypeScript Support

Define session data types:
filename=app/sessions.server.ts

Helper Functions

Create utilities to simplify common session operations:
filename=app/sessions.server.ts
Use in routes:
filename=app/routes/protected.tsx

Advantages

  • No database required - Simplifies deployment and reduces infrastructure
  • Stateless - Works seamlessly in load-balanced environments
  • Fast - No database queries for session data
  • Simple - Easy to set up and maintain

Limitations

Browsers limit cookies to approximately 4KB. Store minimal data:
The commitSession method throws an error if the cookie exceeds the size limit:

Data Included in Every Request

Cookie session data is sent with every request:

Security Considerations

Always Use Secrets

Sign cookies to prevent tampering:

Use HttpOnly Cookies

Prevent XSS attacks:

Enable Secure in Production

Only send cookies over HTTPS:

Use SameSite Protection

Prevent CSRF attacks: