loader

Watch the 📼 Remix Single: Loading data into components

Each route can define a “loader” function that provides data to the route when rendering.

  1. import { json } from "@remix-run/node"; // or cloudflare/deno
  2. export const loader = async () => {
  3. return json({ ok: true });
  4. };

This function is only ever run on the server. On the initial server render, it will provide data to the HTML document. On navigations in the browser, Remix will call the function via fetch from the browser.

This means you can talk directly to your database, use server-only API secrets, etc. Any code that isn’t used to render the UI will be removed from the browser bundle.

Using the database ORM Prisma as an example:

  1. import { useLoaderData } from "@remix-run/react";
  2. import { prisma } from "../db";
  3. export async function loader() {
  4. return json(await prisma.user.findMany());
  5. }
  6. export default function Users() {
  7. const data = useLoaderData<typeof loader>();
  8. return (
  9. <ul>
  10. {data.map((user) => (
  11. <li key={user.id}>{user.name}</li>
  12. ))}
  13. </ul>
  14. );
  15. }

Because prisma is only used in the loader it will be removed from the browser bundle by the compiler, as illustrated by the highlighted lines.

Note that whatever you return from your loader will be exposed to the client, even if the component doesn’t render it. Treat your loaders with the same care as public API endpoints.

Type Safety

You can get type safety over the network for your loader and component with LoaderArgs and useLoaderData<typeof loader>.

  1. import type { LoaderArgs } from "@remix-run/node";
  2. import { json } from "@remix-run/node";
  3. import { useLoaderData } from "@remix-run/react";
  4. export async function loader() {
  5. return json({ name: "Ryan", date: new Date() });
  6. }
  7. export default function SomeRoute() {
  8. const data = useLoaderData<typeof loader>();
  9. }
  • data.name will know that it’s a string
  • data.date will also know that it’s a string even though we passed a date object to json. When data is fetched for client transitions, the values are serialized over the network with JSON.stringify, and the types are aware of that

params

Route params are defined by route file names. If a segment begins with $ like $invoiceId, the value from the URL for that segment will be passed to your loader.

  1. // if the user visits /invoices/123
  2. export async function loader({ params }: LoaderArgs) {
  3. params.invoiceId; // "123"
  4. }

Params are mostly useful for looking up records by ID:

  1. // if the user visits /invoices/123
  2. export async function loader({ params }: LoaderArgs) {
  3. const invoice = await fakeDb.getInvoice(params.invoiceId);
  4. if (!invoice) throw new Response("", { status: 404 });
  5. return json(invoice);
  6. }

request

This is a Fetch Request instance. You can read the MDN docs to see all of its properties.

The most common use cases in loaders are reading headers (like cookies) and URL URLSearchParams from the request:

  1. export async function loader({ request }: LoaderArgs) {
  2. // read a cookie
  3. const cookie = request.headers.get("Cookie");
  4. // parse the search params for `?q=`
  5. const url = new URL(request.url);
  6. const query = url.searchParams.get("q");
  7. }

context

This is the context passed in to your server adapter’s getLoadContext() function. It’s a way to bridge the gap between the adapter’s request/response API with your Remix app.

This API is an escape hatch, it’s uncommon to need it

Using the express adapter as an example:

  1. const {
  2. createRequestHandler,
  3. } = require("@remix-run/express");
  4. app.all(
  5. "*",
  6. createRequestHandler({
  7. getLoadContext(req, res) {
  8. // this becomes the loader context
  9. return { expressUser: req.user };
  10. },
  11. })
  12. );

And then your loader can access it.

  1. export async function loader({ context }: LoaderArgs) {
  2. const { expressUser } = context;
  3. // ...
  4. }

Returning Response Instances

You need to return a Fetch Response from your loader.

  1. export async function loader() {
  2. const users = await db.users.findMany();
  3. const body = JSON.stringify(users);
  4. return new Response(body, {
  5. headers: {
  6. "Content-Type": "application/json",
  7. },
  8. });
  9. }

Using the json helper simplifies this, so you don’t have to construct them yourself, but these two examples are effectively the same!

  1. import { json } from "@remix-run/node"; // or cloudflare/deno
  2. export const loader = async () => {
  3. const users = await fakeDb.users.findMany();
  4. return json(users);
  5. };

You can see how json just does a little of the work to make your loader a lot cleaner. You can also use the json helper to add headers or a status code to your response:

  1. import { json } from "@remix-run/node"; // or cloudflare/deno
  2. export const loader = async ({ params }: LoaderArgs) => {
  3. const user = await fakeDb.project.findOne({
  4. where: { id: params.id },
  5. });
  6. if (!user) {
  7. return json("Project not found", { status: 404 });
  8. }
  9. return json(user);
  10. };

See also:

Throwing Responses in Loaders

Along with returning responses, you can also throw Response objects from your loaders. This allows you to break through the call stack and do one of two things:

  • Redirect to another URL
  • Show an alternate UI with contextual data through the CatchBoundary

Here is a full example showing how you can create utility functions that throw responses to stop code execution in the loader and show an alternative UI.

  1. import { json } from "@remix-run/node"; // or cloudflare/deno
  2. import type { ThrownResponse } from "@remix-run/react";
  3. export type InvoiceNotFoundResponse = ThrownResponse<
  4. 404,
  5. string
  6. >;
  7. export function getInvoice(id, user) {
  8. const invoice = db.invoice.find({ where: { id } });
  9. if (invoice === null) {
  10. throw json("Not Found", { status: 404 });
  11. }
  12. return invoice;
  13. }
  1. import { redirect } from "@remix-run/node"; // or cloudflare/deno
  2. import { getSession } from "./session";
  3. export async function requireUserSession(request) {
  4. const session = await getSession(
  5. request.headers.get("cookie")
  6. );
  7. if (!session) {
  8. // You can throw our helpers like `redirect` and `json` because they
  9. // return `Response` objects. A `redirect` response will redirect to
  10. // another URL, while other responses will trigger the UI rendered
  11. // in the `CatchBoundary`.
  12. throw redirect("/login", 302);
  13. }
  14. return session.get("user");
  15. }
  1. import type { LoaderArgs } from "@remix-run/node"; // or cloudflare/deno
  2. import { json } from "@remix-run/node"; // or cloudflare/deno
  3. import type { ThrownResponse } from "@remix-run/react";
  4. import { useCatch, useLoaderData } from "@remix-run/react";
  5. import { getInvoice } from "~/db";
  6. import type { InvoiceNotFoundResponse } from "~/db";
  7. import { requireUserSession } from "~/http";
  8. type InvoiceCatchData = {
  9. invoiceOwnerEmail: string;
  10. };
  11. type ThrownResponses =
  12. | InvoiceNotFoundResponse
  13. | ThrownResponse<401, InvoiceCatchData>;
  14. export const loader = async ({
  15. params,
  16. request,
  17. }: LoaderArgs) => {
  18. const user = await requireUserSession(request);
  19. const invoice = getInvoice(params.invoiceId);
  20. if (!invoice.userIds.includes(user.id)) {
  21. throw json(
  22. { invoiceOwnerEmail: invoice.owner.email },
  23. { status: 401 }
  24. );
  25. }
  26. return json(invoice);
  27. };
  28. export default function InvoiceRoute() {
  29. const invoice = useLoaderData<Invoice>();
  30. return <InvoiceView invoice={invoice} />;
  31. }
  32. export function CatchBoundary() {
  33. // this returns { data, status, statusText }
  34. const caught = useCatch<ThrownResponses>();
  35. switch (caught.status) {
  36. case 401:
  37. return (
  38. <div>
  39. <p>You don't have access to this invoice.</p>
  40. <p>
  41. Contact {caught.data.invoiceOwnerEmail} to get
  42. access
  43. </p>
  44. </div>
  45. );
  46. case 404:
  47. return <div>Invoice not found!</div>;
  48. }
  49. // You could also `throw new Error("Unknown status in catch boundary")`.
  50. // This will be caught by the closest `ErrorBoundary`.
  51. return (
  52. <div>
  53. Something went wrong: {caught.status}{" "}
  54. {caught.statusText}
  55. </div>
  56. );
  57. }