Learn Remix · 9/13

Authentication & Session Management

8 min read

Authentication & Session Management in Remix authentication and session management in Remix.

Welcome, intrepid web developer, to the crucial topic of keeping your users' data safe and sound: Authentication and Session Management in Remix! 🔐

Think of your website as an exclusive clubhouse. You need a bouncer (authentication) to check IDs at the door and a way to remember who's who once they're inside (session management). Without these, chaos ensues! Anyone could wander in, and you'd have no idea who is ordering what at the digital snack bar.

In this guide, we'll walk through how Remix helps you build a robust and secure system for managing user access.

1. Understanding Remix Sessions and Cookie Storage 🍪

The Problem: How do we "remember" a user across multiple requests? HTTP, the protocol of the web, is stateless. This means each time a user clicks a link or submits a form, the server sees it as a brand new person. It's like having a conversation with someone who has severe short-term memory loss.

The Solution: Sessions and Cookies! A session is like a temporary membership card for your user. When they log in, you give them this card. A cookie is a small piece of data sent from a website and stored on the user's computer by the user's web browser. It's the physical card itself that the user carries around.

In Remix, we use createCookieSessionStorage to manage sessions where the data is stored directly in the cookie. This is super convenient because you don't need a separate database to store session information. However, be mindful of the 4kb size limit for cookies.

Let's see it in action:

First, we'll create a file to manage our session storage. It's a good practice to keep this in a separate file, like app/sessions.server.ts.

typescript
// app/sessions.server.ts
import { createCookieSessionStorage } from "@remix-run/node";

type SessionData = {
  userId: string;
};

type SessionFlashData = {
  error: string;
};

export const { getSession, commitSession, destroySession } =
  createCookieSessionStorage<SessionData, SessionFlashData>({
    cookie: {
      name: "__session",
      httpOnly: true,
      path: "/",
      sameSite: "lax",
      secrets: [process.env.SESSION_SECRET], // This should be a secret string
      secure: process.env.NODE_ENV === "production",
    },
  });

What's happening here?

  • createCookieSessionStorage: This function from Remix creates the necessary tools for managing our cookie-based session.
  • cookie: This object configures our cookie.
    • name: The name of our cookie.
    • httpOnly: This is a security measure that prevents JavaScript from accessing the cookie.
    • path: The cookie will be available on all routes.
    • sameSite: Helps prevent Cross-Site Request Forgery (CSRF) attacks.
    • secrets: An array of strings used to sign the cookie, preventing tampering.
    • secure: Ensures the cookie is only sent over HTTPS in production.

We now have three important functions: getSession, commitSession, and destroySession.

  • getSession(cookieHeader): Reads the cookie from the request and gives us the session data.
  • commitSession(session): Takes our session data and prepares it to be sent back to the browser in a Set-Cookie header.
  • destroySession(session): Invalidates the session.

Think of createCookieSessionStorage as ordering a custom-made rubber stamp (__session). commitSession is you stamping a user's hand, and getSession is you checking their stamp later. destroySession is like washing the stamp off their hand when they leave.

2. Creating a Login Flow: Validating Users and Setting Session Data 🚪

The Problem: Now that we can create sessions, how do we handle a user trying to log in? We need to check their credentials and, if they're correct, give them a session.

The Solution: Remix's action function is the perfect place for this. When a user submits a login form, the action function on that route will be called. Inside the action, we can validate the user's input and, if it's valid, create a session for them.

Example Login Route (app/routes/login.tsx):

typescript
// app/routes/login.tsx
import { ActionFunctionArgs, json, redirect } from "@remix-run/node";
import { Form, useActionData } from "@remix-run/react";
import { getSession, commitSession } from "~/sessions.server";
import { login } from "~/models/user.server"; // A mock function to find a user

export async function action({ request }: ActionFunctionArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  const formData = await request.formData();
  const { email, password } = Object.fromEntries(formData);

  // You should add proper validation here!
  if (typeof email !== "string" || typeof password !== "string") {
    return json({ error: "Invalid form data" }, { status: 400 });
  }

  const user = await login({ email, password });

  if (!user) {
    return json({ error: "Invalid email or password" }, { status: 401 });
  }

  session.set("userId", user.id);

  return redirect("/", {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });
}

export default function LoginPage() {
  const actionData = useActionData<typeof action>();

  return (
    <div>
      <h1>Login</h1>
      <Form method="post">
        <input type="email" name="email" required />
        <input type="password" name="password" required />
        <button type="submit">Log In</button>
      </Form>
      {actionData?.error && <p>{actionData.error}</p>}
    </div>
  );
}

Breakdown of the action function:

  1. We get the current session.
  2. We get the form data submitted by the user.
  3. We perform some basic validation. In a real-world application, you'd use a library like Zod for more robust validation.
  4. We call a login function (which you would create) to check the user's credentials against your database.
  5. If the login is unsuccessful, we return a JSON response with an error message.
  6. If the login is successful, we use session.set("userId", user.id) to store the user's ID in the session.
  7. Finally, we redirect the user to the homepage and include the Set-Cookie header with our newly committed session.

It's like the bouncer checking the ID, and if it's valid, they give the person a wristband with a unique number on it.

3. Protecting Routes: Checking Authentication Status in Loaders 🛡️

The Problem: We've let our user in, but how do we make sure only people with a valid wristband can access the VIP section?

The Solution: Remix's loader functions are perfect for this. Loaders run on the server before a route is rendered. We can check for a valid session in the loader of a protected route. If the user isn't logged in, we can redirect them to the login page.

Example of a Protected Route (app/routes/dashboard.tsx):

typescript
// app/routes/dashboard.tsx
import { LoaderFunctionArgs, json, redirect } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { getSession } from "~/sessions.server";
import { getUserById } from "~/models/user.server"; // A mock function to get user by ID

export async function loader({ request }: LoaderFunctionArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  const userId = session.get("userId");

  if (!userId) {
    return redirect("/login");
  }

  const user = await getUserById(userId);

  if (!user) {
    // This could happen if the user was deleted after logging in
    return redirect("/login");
  }

  return json({ user });
}

export default function Dashboard() {
  const { user } = useLoaderData<typeof loader>();

  return <h1>Welcome, {user.email}!</h1>;
}

Inside the loader:

  1. We get the session from the request's cookies.
  2. We try to get the userId from the session data.
  3. If there's no userId, it means the user isn't logged in, so we redirect them to the login page.
  4. We then try to fetch the user from the database using the userId.
  5. If the user doesn't exist, we also redirect to the login page.
  6. If everything checks out, we return the user's data as JSON.

This is our bouncer at the VIP section door, checking everyone's wristband. No wristband, no entry!

4. Logging Out: Destroying Sessions Securely 💥

The Problem: Our user has had a great time at the clubhouse, but now they want to leave. How do we make sure their wristband is removed and can't be used by someone else?

The Solution: We need to destroy the session. This should always be done in an action function, typically in response to a form submission (e.g., clicking a "Logout" button). It's a security best practice to perform mutations like logging out in an action to prevent CSRF attacks.

Example Logout Route (app/routes/logout.ts):

typescript
// app/routes/logout.ts
import { ActionFunctionArgs, redirect } from "@remix-run/node";
import { getSession, destroySession } from "~/sessions.server";

export async function action({ request }: ActionFunctionArgs) {
  const session = await getSession(request.headers.get("Cookie"));

  return redirect("/", {
    headers: {
      "Set-Cookie": await destroySession(session),
    },
  });
}

A Simple but Secure Logout:

  1. We have a route that only exports an action. This is because we don't need to render any UI for logging out; it's purely a server-side operation.
  2. We get the current session.
  3. We redirect the user to the homepage and, in the headers, we send back a Set-Cookie instruction to destroy the session.

This is like the bouncer at the exit, cutting off the user's wristband as they leave, ensuring it can't be reused.

An interesting fact: The remix-auth package is a popular community-driven solution that builds upon these fundamental concepts to provide a more comprehensive authentication system with support for various strategies like username/password, OAuth, and more.


And there you have it! The fundamentals of authentication and session management in Remix. By understanding these core concepts, you're well on your way to building secure and user-friendly web applications.

Additional Resources 📚

Challenge

You are building a protected dashboard route in a Remix application. Your task is to implement the full authentication and session management logic for this route within a single file.

Requirements:

  1. Configure Session Storage:

    • Below the imports, create and export a sessionStorage object using createCookieSessionStorage.
    • The session cookie must be named __session.
    • It must be configured with the following security options:
      • A secret key from the SESSION_SECRET environment variable.
      • httpOnly: true
      • path: "/"
      • sameSite: "lax"
      • secure: process.env.NODE_ENV === "production"
  2. Protect the Route:

    • Implement the loader function.
    • It should get the session from the incoming request.
    • If a userId is not present in the session, it must redirect the user to /login.
    • If a userId is present, it should return an empty JSON object.
  3. Handle Login and Logout:

    • Implement the action function to handle two different form submissions based on a hidden _action field.
    • Login (POST):
      • When a form with _action: "login" is submitted, get the email and password from the form data.
      • Use the provided login(email, password) function to authenticate the user.
      • If authentication is successful, get the session, set the userId in the session, and redirect to the current route (/dashboard) with the committed session cookie.
    • Logout (POST):
      • When a form with _action: "logout" is submitted, get the current session.
      • Redirect the user to /login with the Set-Cookie header that destroys the session.

Expected result

Your code should correctly implement a Remix route with session-based authentication.

  1. sessionStorage Configuration:

    • You should have an exported sessionStorage constant initialized with createCookieSessionStorage.
    • The configuration object passed to it must contain a cookie object with all the required properties: name, secrets, httpOnly, path, sameSite, and secure.
  2. loader Function:

    • The loader function must call sessionStorage.getSession with the request.headers.get("Cookie").
    • It must check if session.has("userId") is false.
    • If it is, the function must return a redirect to /login.
    • Otherwise, it should return json({}).
  3. action Function:

    • The action must first get the session from the request.
    • It must read the form data using request.formData().
    • It should use formData.get("_action") to differentiate between login and logout.
    • For the 'login' action:
      • It retrieves email and password from the form data.
      • It calls the login function.
      • On a successful login, it calls session.set("userId", user.id).
      • It returns a redirect to /dashboard, with a headers object containing the Set-Cookie value from sessionStorage.commitSession(session).
    • For the 'logout' action:
      • It returns a redirect to /login, with a headers object containing the Set-Cookie value from sessionStorage.destroySession(session).
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.