Frequently Asked Questions

How can I have a parent route loader validate the user and protect all child routes?

You can’t 😅. During a client-side transition, to make your app as speedy as possible, Remix will call all of your loaders in parallel, in separate fetch requests. Each one of them needs to have its own authentication check.

This is probably not different than what you were doing before Remix, it might just be more obvious now. Outside of Remix, when you make multiple fetches to your “API Routes”, each of those endpoints needs to validate the user session. In other words, Remix route loaders are their own “API Route” and must be treated as such.

We recommend you create a function that validates the user session that can be added to any routes that require it.

  1. import {
  2. createCookieSessionStorage,
  3. redirect,
  4. } from "@remix-run/node"; // or cloudflare/deno
  5. // somewhere you've got a session storage
  6. const { getSession } = createCookieSessionStorage();
  7. export async function requireUserSession(request) {
  8. // get the session
  9. const cookie = request.headers.get("cookie");
  10. const session = await getSession(cookie);
  11. // validate the session, `userId` is just an example, use whatever value you
  12. // put in the session when the user authenticated
  13. if (!session.has("userId")) {
  14. // if there is no user session, redirect to login
  15. throw redirect("/login");
  16. }
  17. return session;
  18. }

And now in any loader or action that requires a user session, you can call the function.

  1. export async function loader({ request }: LoaderArgs) {
  2. // if the user isn't authenticated, this will redirect to login
  3. const session = await requireUserSession(request);
  4. // otherwise the code continues to execute
  5. const projects = await fakeDb.projects.scan({
  6. userId: session.get("userId"),
  7. });
  8. return json(projects);
  9. }

Even if you don’t need the session information, the function will still protect the route:

  1. export async function loader({ request }: LoaderArgs) {
  2. await requireUserSession(request);
  3. // continue
  4. }

How do I handle multiple forms in one route?

Watch on YouTube

In HTML, forms can post to any URL with the action prop and the app will navigate there:

  1. <Form action="/some/where" />

In Remix the action defaults to the route that the form is rendered in, making it easy to co-locate the UI and the server code that handles it. Developers often wonder how you can handle multiple actions in this scenario. You have two choices:

  1. Send a form field to determine the action you want to take
  2. Post to a different route and redirect back to the original

We find option (1) to be the simplest because you don’t have to mess around with sessions to get validation errors back to the UI.

HTML buttons can send a value, so it’s the easiest way to implement this:

  1. export async function action({ request }: ActionArgs) {
  2. const formData = await request.formData();
  3. const intent = formData.get("intent");
  4. switch (intent) {
  5. case "update": {
  6. // do your update
  7. return updateProjectName(formData.get("name"));
  8. }
  9. case "delete": {
  10. // do your delete
  11. return deleteStuff(formData);
  12. }
  13. default: {
  14. throw new Error("Unexpected action");
  15. }
  16. }
  17. }
  18. export default function Projects() {
  19. const project = useLoaderData<typeof loader>();
  20. return (
  21. <>
  22. <h2>Update Project</h2>
  23. <Form method="post">
  24. <label>
  25. Project name:{" "}
  26. <input
  27. type="text"
  28. name="name"
  29. defaultValue={project.name}
  30. />
  31. </label>
  32. <button type="submit" name="intent" value="update">
  33. Update
  34. </button>
  35. </Form>
  36. <Form method="post">
  37. <button type="submit" name="intent" value="delete">
  38. Delete
  39. </button>
  40. </Form>
  41. </>
  42. );
  43. }

How can I have structured data in a form?

If you’re used to doing fetches with a content type of application/json, you may wonder how forms fit into this. FormData is a bit different than JSON.

  • It can’t have nested data, it’s just “key value”.
  • It can have multiple entries on one key, unlike JSON.

If you’re wanting to send structured data simply to post arrays, you can use the same key on multiple inputs:

  1. <Form method="post">
  2. <p>Select the categories for this video:</p>
  3. <label>
  4. <input type="checkbox" name="category" value="comedy" />{" "}
  5. Comedy
  6. </label>
  7. <label>
  8. <input type="checkbox" name="category" value="music" />{" "}
  9. Music
  10. </label>
  11. <label>
  12. <input type="checkbox" name="category" value="howto" />{" "}
  13. How-To
  14. </label>
  15. </Form>

Each checkbox has the name: “category”. Since FormData can have multiple values on the same key, you don’t need JSON for this. Access the checkbox values with formData.getAll() in your action.

  1. export async function action({ request }: ActionArgs) {
  2. const formData = await request.formData();
  3. const categories = formData.getAll("category");
  4. // ["comedy", "music"]
  5. }

Using the same input name and formData.getAll() covers most cases for wanting to submit structured data in your forms.

If you still want to submit nested structures as well, you can use non-standard form-field naming conventions and the query-string package from npm:

  1. <>
  2. // arrays with []
  3. <input name="category[]" value="comedy" />
  4. <input name="category[]" value="comedy" />
  5. // nested structures parentKey[childKey]
  6. <input name="user[name]" value="Ryan" />
  7. </>

And then in your action:

  1. import queryString from "query-string";
  2. // in your action:
  3. export async function action({ request }: ActionArgs) {
  4. // use `request.text()`, not `request.formData` to get the form data as a url
  5. // encoded form query string
  6. const formQueryString = await request.text();
  7. // parse it into an object
  8. const obj = queryString.parse(formQueryString);
  9. }

Some folks even dump their JSON into a hidden field. Note that this approach won’t work with progressive enhancement. If that’s not important to your app, this is an easy way to send structured data.

  1. <input
  2. type="hidden"
  3. name="json"
  4. value={JSON.stringify(obj)}
  5. />

And then parse it in the action:

  1. export async function action({ request }: ActionArgs) {
  2. const formData = await request.formData();
  3. const obj = JSON.parse(formData.get("json"));
  4. }

Again, formData.getAll() is often all you need, we encourage you to give it a shot!

What’s the difference between CatchBoundary & ErrorBoundary?

Error boundaries render when your application throws an error and you had no clue it was going to happen. Most apps just go blank or have spinners spin forever. In remix the error boundary renders and you have granular control over it.

Catch boundaries render when you decide in a loader that you can’t proceed down the happy path to render the UI you want (auth required, record not found, etc.), so you throw a response and let some catch boundary up the tree handle it.