liveBook · Manning

Encrypted cookie

As explained in React in Depth

An encrypted cookie is a web cookie whose contents are protected by encryption so that unauthorized readers cannot interpret its data.

An encrypted cookie protects stored cookie data from unauthorized interpretation. In Remix, the encryption secret must remain on the server, making cookie reads and writes server-only. section 11.3.3

Use encrypted cookies when:

  • A browser cookie contains private preferences such as a shipping address or saved login email. section 11.3.3
  • Server-rendered output must use the same persisted setting as the client to preserve hydration. section 11.3.3
  • The application can round-trip updates through the server instead of exposing the encryption key to browser JavaScript. section 11.3.3

Remix temperature preference

Define a server cookie with createCookie("temperature", { maxAge }), parse the incoming Cookie header with temperatureCookie.parse(cookieHeader), and persist changes with temperatureCookie.serialize(!isCelsius). A form action can return the serialized value through Set-Cookie. section 11.3.3

Figure 11.17 The API for setting and reading cookies is a little bit less obvious in Remix, using parse() to read and serialize() to set. The button to change scale is a submit button in a form. If JavaScript is enabled, Remix kicks in and hijacks the form, sending only data back and forth to the server. If not, the format change still works after the whole page reloads.
figure

Compare Remix parse and serialize operations with form submission behavior when JavaScript is enabled or absent. section 11.3.3

How React in Depth covers it

How deep it goes
Explains the server-only consequence and demonstrates parsing, serialization, form submission, and response headers.
Examples
Uses temperature and time preferences, city routes, createCookie, parse, serialize, and Set-Cookie responses.
What it assumes
Assumes familiarity with browser cookies, server requests, forms, and JavaScript-enabled versus JavaScript-free navigation.
What you can do after
Operate encrypted cookies through Remix server utilities, form actions, request headers, and response serialization.
How it connects
Connects cookies with server-side rendering, hydration, forms, HTTP headers, and JavaScript independence.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React in Depth. The section links point to the parts of the book it draws on.