0
0
RemixHow-ToBeginner · 4 min read

How to Use Session in Remix: Simple Guide with Example

In Remix, use createCookieSessionStorage to create session storage and manage sessions. You read, write, and commit sessions via the request and response headers using getSession, session.set, and commitSession methods.
📐

Syntax

To use sessions in Remix, first create a session storage with createCookieSessionStorage. Then, use getSession to read the session from the request, modify it with session.set, and finally use commitSession to save changes in the response headers.

  • createCookieSessionStorage: Initializes cookie-based session storage.
  • getSession(request.headers.get('Cookie')): Reads the session from the incoming request.
  • session.set(key, value): Sets a value in the session.
  • commitSession(session): Returns a header to save the session cookie in the response.
typescript
import { createCookieSessionStorage } from "@remix-run/node";

const sessionStorage = createCookieSessionStorage({
  cookie: {
    name: "my_session",
    secrets: ["s3cret1"],
    sameSite: "lax",
    path: "/",
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
  },
});

// Usage in loader or action
export async function loader({ request }) {
  const session = await sessionStorage.getSession(request.headers.get("Cookie"));
  const user = session.get("user");
  return { user };
}

export async function action({ request }) {
  const session = await sessionStorage.getSession(request.headers.get("Cookie"));
  session.set("user", "Alice");
  return new Response(null, {
    headers: {
      "Set-Cookie": await sessionStorage.commitSession(session),
    },
  });
}
💻

Example

This example shows a simple Remix route that sets a username in the session on form submission and reads it on page load.

typescript
import { createCookieSessionStorage } from "@remix-run/node";
import { json } from "@remix-run/node";
import { Form, useLoaderData } from "@remix-run/react";

const sessionStorage = createCookieSessionStorage({
  cookie: {
    name: "session",
    secrets: ["super-secret-key"],
    sameSite: "lax",
    path: "/",
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
  },
});

export async function loader({ request }) {
  const session = await sessionStorage.getSession(request.headers.get("Cookie"));
  const user = session.get("user") || null;
  return json({ user });
}

export async function action({ request }) {
  const formData = await request.formData();
  const user = formData.get("username");
  const session = await sessionStorage.getSession(request.headers.get("Cookie"));
  session.set("user", user);
  return new Response(null, {
    status: 302,
    headers: {
      "Location": "/",
      "Set-Cookie": await sessionStorage.commitSession(session),
    },
  });
}

export default function Index() {
  const { user } = useLoaderData();
  return (
    <main>
      <h1>Welcome {user ? user : "Guest"}!</h1>
      <Form method="post">
        <input type="text" name="username" placeholder="Enter your name" required />
        <button type="submit">Set User</button>
      </Form>
    </main>
  );
}
Output
<main>\n <h1>Welcome Guest!</h1>\n <form method="post">\n <input type="text" name="username" placeholder="Enter your name" required />\n <button type="submit">Set User</button>\n </form>\n</main>
⚠️

Common Pitfalls

  • Forgetting to include Set-Cookie header in the response will not save session changes.
  • Not using await with getSession or commitSession causes errors.
  • Using insecure cookie settings in production can expose session data.
  • Trying to read session data before calling getSession will fail.
typescript
/* Wrong: Missing Set-Cookie header, session changes won't persist */
export async function action({ request }) {
  const session = await sessionStorage.getSession(request.headers.get("Cookie"));
  session.set("user", "Bob");
  return new Response("User set"); // No Set-Cookie header here
}

/* Right: Commit session with Set-Cookie header */
export async function action({ request }) {
  const session = await sessionStorage.getSession(request.headers.get("Cookie"));
  session.set("user", "Bob");
  return new Response("User set", {
    headers: {
      "Set-Cookie": await sessionStorage.commitSession(session),
    },
  });
}
📊

Quick Reference

  • createCookieSessionStorage(options): Create session storage with cookie options.
  • getSession(cookieHeader): Read session from request cookie header.
  • session.get(key): Get a value from session.
  • session.set(key, value): Set a value in session.
  • commitSession(session): Get cookie header to save session.
  • destroySession(session): Clear session cookie.

Key Takeaways

Use createCookieSessionStorage to set up session storage with secure cookie options.
Always await getSession and commitSession to properly read and save sessions.
Include the Set-Cookie header in your response to persist session changes.
Use session.set and session.get to modify and access session data.
Avoid insecure cookie settings in production to protect user data.