Show a flash message in Remix after form submission

Let's learn how to show a flash message in Remix after form submission.

Remix provides a way to store data in the session that will be unset the first time it is read.

This is useful for showing a flash message after a form submission after redirecting to a new page.

For example, after a user submits a form to create a new user, we can redirect them to the welcome page and show a flash message.

Let's create a session wrapper to make it easier to use.

Create a new file app/sessions.ts and add the following code.

import { createCookieSessionStorage } from "@remix-run/node";

const { getSession, commitSession } = createCookieSessionStorage({
  cookie: {
    name: "__session",
    httpOnly: true,
    maxAge: 60,
    path: "/",
    sameSite: "lax",
    secrets: ["secrets"],
    secure: true,
  },
});

export { getSession, commitSession };

The method createCookieSessionStorage creates a session storage that uses cookies to store the session data.

The getSession method retrieves the current session from the incoming request's Cookie header.

The commitSession method commits the session and returns the session cookie to be set in the response.

Add a new route /signup to create a new user with a form.

The action method handles the form submission and redirects to the /welcome page with a flash message.

import type { ActionArgs } from "@remix-run/node";
import { Form } from "@remix-run/react";
import { redirect } from "@remix-run/node";

import { getSession, commitSession } from "~/sessions";

export async function action({ request }: ActionArgs) {
  // Retrieves the current session from the incoming request's Cookie header
  const session = await getSession(request.headers.get("Cookie"));

  // Set a session value to be used in the next request
  session.flash("message", "Welcome to Remix!");

  // Redirect to the welcome page and set the session cookie
  return redirect("/welcome", {
    headers: {
      "Set-Cookie": await commitSession(session),
    },
  });
}

export default function User() {
  return (
    <>
      <Form method="post">
        <input type="text" name="name" placeholder="Name" />
        <input type="email" name="email" placeholder="Email" />
        <input type="password" name="password" placeholder="Password" />
        <button type="submit">Create User</button>
      </Form>
    </>
  );
}

session.flash method sets a session value that will be unset the first time it is read.

Add a new route /welcome to show the flash message.

The loader method retrieves the session value set in the previous request and returns it to the client.

Use the useLoaderData hook to retrieve the message from the loader data and show it in the page.

import type { LoaderArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";

import { getSession, commitSession } from "~/sessions";

export async function loader({ request }: LoaderArgs) {
  // Retrieves the current session from the incoming request's Cookie header
  const session = await getSession(request.headers.get("Cookie"));

  // Retrieve the session value set in the previous request
  const message = session.get("message") || "No message found";

  // Commit the session and return the message
  return json(
    { message },
    {
      headers: {
        "Set-Cookie": await commitSession(session),
      },
    }
  );
}

export default function User() {
  // Retrieve the message from the loader data
  const { message } = useLoaderData<typeof loader>();

  return <p>{message}</p>;
}

If you refresh the page, the message will be gone and a default message will be shown.

More Articles

  1. Use Remix Action to handle form submission
  2. Use Remix Loader to fetch data from an external API
  3. Validating form data in Remix using Zod and Action function
  4. Add a search form in Remix with data fetching
  5. Show a flash message in Remix after form submission
  6. Discover the best SaaS Starter Kits based on Remix