Cookies

A cookie is a small piece of information that your server sends someone in a HTTP response that their browser will send back on subsequent requests. This technique is a fundamental building block of many interactive websites that adds state so you can build authentication (see sessions), shopping carts, user preferences, and many other features that require remembering who is “logged in”.

Remix’s Cookie interface provides a logical, reusable container for cookie metadata.

Using cookies

While you may create these cookies manually, it is more common to use a session storage.

In Remix, you will typically work with cookies in your loader and/or action functions (see mutations), since those are the places where you need to read and write data.

Let’s say you have a banner on your e-commerce site that prompts users to check out the items you currently have on sale. The banner spans the top of your homepage, and includes a button on the side that allows the user to dismiss the banner so they don’t see it for at least another week.

First, create a cookie:

  1. import { createCookie } from "@remix-run/node"; // or cloudflare/deno
  2. export const userPrefs = createCookie("user-prefs", {
  3. maxAge: 604_800, // one week
  4. });

Then, you can import the cookie and use it in your loader and/or action. The loader in this case just checks the value of the user preference so you can use it in your component for deciding whether to render the banner. When the button is clicked, the <form> calls the action on the server and reloads the page without the banner.

Note: We recommend (for now) that you create all the cookies your app needs in a *.server.ts file and import them into your route modules. This allows the Remix compiler to correctly prune these imports out of the browser build where they are not needed. We hope to eventually remove this caveat.

  1. import type {
  2. ActionArgs,
  3. LoaderArgs,
  4. } from "@remix-run/node"; // or cloudflare/deno
  5. import { json, redirect } from "@remix-run/node"; // or cloudflare/deno
  6. import {
  7. useLoaderData,
  8. Link,
  9. Form,
  10. } from "@remix-run/react";
  11. import { userPrefs } from "~/cookies.server";
  12. export async function loader({ request }: LoaderArgs) {
  13. const cookieHeader = request.headers.get("Cookie");
  14. const cookie =
  15. (await userPrefs.parse(cookieHeader)) || {};
  16. return json({ showBanner: cookie.showBanner });
  17. }
  18. export async function action({ request }: ActionArgs) {
  19. const cookieHeader = request.headers.get("Cookie");
  20. const cookie =
  21. (await userPrefs.parse(cookieHeader)) || {};
  22. const bodyParams = await request.formData();
  23. if (bodyParams.get("bannerVisibility") === "hidden") {
  24. cookie.showBanner = false;
  25. }
  26. return redirect("/", {
  27. headers: {
  28. "Set-Cookie": await userPrefs.serialize(cookie),
  29. },
  30. });
  31. }
  32. export default function Home() {
  33. const { showBanner } = useLoaderData<typeof loader>();
  34. return (
  35. <div>
  36. {showBanner ? (
  37. <div>
  38. <Link to="/sale">Don't miss our sale!</Link>
  39. <Form method="post">
  40. <input
  41. type="hidden"
  42. name="bannerVisibility"
  43. value="hidden"
  44. />
  45. <button type="submit">Hide</button>
  46. </Form>
  47. </div>
  48. ) : null}
  49. <h1>Welcome!</h1>
  50. </div>
  51. );
  52. }

Cookies have several attributes that control when they expire, how they are accessed, and where they are sent. Any of these attributes may be specified either in createCookie(name, options), or during serialize() when the Set-Cookie header is generated.

  1. const cookie = createCookie("user-prefs", {
  2. // These are defaults for this cookie.
  3. domain: "remix.run",
  4. path: "/",
  5. sameSite: "lax",
  6. httpOnly: true,
  7. secure: true,
  8. expires: new Date(Date.now() + 60_000),
  9. maxAge: 60,
  10. });
  11. // You can either use the defaults:
  12. cookie.serialize(userPrefs);
  13. // Or override individual ones as needed:
  14. cookie.serialize(userPrefs, { sameSite: "strict" });

Please read more info about these attributes to get a better understanding of what they do.

Signing cookies

It is possible to sign a cookie to automatically verify its contents when it is received. Since it’s relatively easy to spoof HTTP headers, this is a good idea for any information that you do not want someone to be able to fake, like authentication information (see sessions).

To sign a cookie, provide one or more secrets when you first create the cookie:

  1. const cookie = createCookie("user-prefs", {
  2. secrets: ["s3cret1"],
  3. });

Cookies that have one or more secrets will be stored and verified in a way that ensures the cookie’s integrity.

Secrets may be rotated by adding new secrets to the front of the secrets array. Cookies that have been signed with old secrets will still be decoded successfully in cookie.parse(), and the newest secret (the first one in the array) will always be used to sign outgoing cookies created in cookie.serialize().

  1. export const cookie = createCookie("user-prefs", {
  2. secrets: ["n3wsecr3t", "olds3cret"],
  3. });
  1. import { cookie } from "~/cookies.server";
  2. export async function loader({ request }: LoaderArgs) {
  3. const oldCookie = request.headers.get("Cookie");
  4. // oldCookie may have been signed with "olds3cret", but still parses ok
  5. const value = await cookie.parse(oldCookie);
  6. new Response("...", {
  7. headers: {
  8. // Set-Cookie is signed with "n3wsecr3t"
  9. "Set-Cookie": await cookie.serialize(value),
  10. },
  11. });
  12. }

createCookie

Creates a logical container for managing a browser cookie from the server.

  1. import { createCookie } from "@remix-run/node"; // or cloudflare/deno
  2. const cookie = createCookie("cookie-name", {
  3. // all of these are optional defaults that can be overridden at runtime
  4. domain: "remix.run",
  5. expires: new Date(Date.now() + 60_000),
  6. httpOnly: true,
  7. maxAge: 60,
  8. path: "/",
  9. sameSite: "lax",
  10. secrets: ["s3cret1"],
  11. secure: true,
  12. });

To learn more about each attribute, please see the MDN Set-Cookie docs.

isCookie

Returns true if an object is a Remix cookie container.

  1. import { isCookie } from "@remix-run/node"; // or cloudflare/deno
  2. const cookie = createCookie("user-prefs");
  3. console.log(isCookie(cookie));
  4. // true

A cookie container is returned from createCookie and has a handful of properties and methods.

  1. const cookie = createCookie(name);
  2. cookie.name;
  3. cookie.parse();
  4. // etc.

The name of the cookie, used in Cookie and Set-Cookie HTTP headers.

Extracts and returns the value of this cookie in a given Cookie header.

  1. const value = await cookie.parse(
  2. request.headers.get("Cookie")
  3. );

Serializes a value and combines it with this cookie’s options to create a Set-Cookie header, suitable for use in an outgoing Response.

  1. new Response("...", {
  2. headers: {
  3. "Set-Cookie": await cookie.serialize({
  4. showBanner: true,
  5. }),
  6. },
  7. });

Will be true if the cookie uses any secrets, false otherwise.

  1. let cookie = createCookie("user-prefs");
  2. console.log(cookie.isSigned); // false
  3. cookie = createCookie("user-prefs", {
  4. secrets: ["soopersekrit"],
  5. });
  6. console.log(cookie.isSigned); // true

The Date on which this cookie expires. Note that if a cookie has both maxAge and expires, this value will be the date at the current time plus the maxAge value since Max-Age takes precedence over Expires.

  1. const cookie = createCookie("user-prefs", {
  2. expires: new Date("2021-01-01"),
  3. });
  4. console.log(cookie.expires); // "2020-01-01T00:00:00.000Z"