Learn Remix · 3/13

Data Loading: Fetching on the Server

6 min read

⚙️ Data Loading: Fetching on the Server

Welcome, intrepid coder, to the server-side! You've been battling it out on the client, but now it's time to level up and fetch data where the magic really happens. In Remix, we do this primarily with a special function called a loader.

The Problem: In traditional React apps (like those made with Create React App), you often fetch data inside a useEffect hook. This happens on the client-side after the initial page load. This can lead to loading spinners and a less-than-ideal user experience. Also, what if you need to access a database or use secret API keys? You can't do that safely on the client.

The Solution: Remix introduces the concept of loader functions. These are functions that run exclusively on the server. This means you can talk directly to your database, use server-only API secrets, and prepare all the data your component needs before it even renders. The result? Faster page loads and a more secure application.


1. The loader Function: Server-Side Data Fetching Basics

Think of a loader function as a dedicated data provider for a specific route. When a user navigates to a route, Remix will execute its loader function on the server and make the data available to your component.

Here's the simplest loader you can imagine:

typescript
// app/routes/some-route.tsx
import { json } from "@remix-run/node";

export async function loader() {
  return json({ message: "Hello from the server! 👋" });
}

What's happening here?

  • We export an async function named loader.
  • We use the json helper from @remix-run/node to return a JSON response. This is the standard way to send data from your loader to your component.

Now, how do we get this data in our component? We'll dive deeper into that in a bit, but for now, know that the data from the loader is made available through a hook called useLoaderData.

Fun Fact: Any code that is only used inside your loader function will be automatically removed from the browser bundle by the Remix compiler. This is a fantastic optimization that keeps your client-side code lean and mean!


2. Reading URL Parameters and Request Context in Loaders

Most of the time, you'll need to fetch data based on something in the URL or details about the incoming request. Loaders are equipped to handle this with ease.

Reading URL Parameters (params)

Let's say you have a route to display a specific product, and the URL looks like /products/123. In Remix, you would create a file at app/routes/products.$productId.tsx. The $ signifies a dynamic segment.

The value of this dynamic segment is available inside your loader via the params object.

typescript
// app/routes/products.$productId.tsx
import { json } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/node";

export async function loader({ params }: LoaderFunctionArgs) {
  const productId = params.productId; // "123"
  // Now you can fetch the product with this ID
  const product = await getProductById(productId);
  return json({ product });
}

// A placeholder function for fetching a product
async function getProductById(id: string | undefined) {
  // In a real app, you'd fetch this from a database
  const products = [
    { id: "123", name: "Cool Gadget", price: 99.99 },
    { id: "456", name: "Awesome Widget", price: 49.99 },
  ];
  return products.find(p => p.id === id);
}

The request Object

Your loader also receives a request object, which is a standard Fetch Request instance. This is incredibly useful for things like:

  • Reading cookies from the request headers.
  • Getting URL search parameters (the part after the ?).

Imagine a URL like /products?brand=acme. You can access the brand parameter like this:

typescript
// app/routes/products.tsx
import { json } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/node";

export async function loader({ request }: LoaderFunctionArgs) {
  const url = new URL(request.url);
  const brand = url.searchParams.get("brand");

  // Fetch products filtered by brand
  const products = await getProductsByBrand(brand);
  return json({ products, brand });
}

// A placeholder function for fetching products by brand
async function getProductsByBrand(brand: string | null) {
  // ... database query logic
  return [{ id: "789", name: `A Product from ${brand || 'all brands'}`, price: 19.99 }];
}

3. Returning JSON and Rendering with useLoaderData

So, you've fetched your data on the server. Now, how do you get it into your React component on the client? Enter the useLoaderData hook.

This hook, provided by @remix-run/react, gives you access to the serialized data returned from your route's loader function.

Let's put it all together with our product example:

typescript
// app/routes/products.$productId.tsx
import { json } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";

export async function loader({ params }: LoaderFunctionArgs) {
  const productId = params.productId;
  const product = await getProductById(productId);
  if (!product) {
    throw new Response("Product Not Found", { status: 404 });
  }
  return json({ product });
}

export default function ProductPage() {
  const { product } = useLoaderData<typeof loader>();

  return (
    <div>
      <h1>{product.name}</h1>
      <p>${product.price}</p>
    </div>
  );
}

// Placeholder function
async function getProductById(id: string | undefined) {
  const products = [
    { id: "123", name: "Cool Gadget", price: 99.99 },
    { id: "456", name: "Awesome Widget", price: 49.99 },
  ];
  return products.find(p => p.id === id);
}

Key things to notice:

  • We import useLoaderData from @remix-run/react.
  • We call useLoaderData<typeof loader>() inside our component to get the data. The typeof loader part is a TypeScript trick for type safety, which we'll cover next!
  • If the product isn't found, we can throw a Response. This is a powerful feature of Remix for handling errors gracefully.

4. Typing Loaders: Ensuring Type Safety Between Server and Client

One of the most powerful features when using TypeScript with Remix is the ability to have end-to-end type safety. This means the data you fetch in your server-side loader will have the correct types in your client-side component.

The magic happens with this line:

typescript
const data = useLoaderData<typeof loader>();

By passing typeof loader as a generic to useLoaderData, TypeScript can infer the return type of your loader function and apply it to the data variable. This eliminates a whole class of bugs and makes your code much easier to reason about and refactor.

Let's break down why this is so cool:

Imagine you refactor your loader to return a different data shape:

typescript
export async function loader() {
  // ... fetching logic
  // Oops, we changed the shape!
  return json({ productData: product });
}

Now, in your component:

typescript
export default function ProductPage() {
  // TypeScript will now throw an error here because `product` doesn't exist on the type!
  const { product } = useLoaderData<typeof loader>();

  // ...
}

Without this type inference, you would have a runtime error when trying to access product.name. With it, you get an error right in your editor!

Industry Practice: Always use useLoaderData<typeof loader>() to ensure your server and client code stay in sync. It's a simple step that saves a lot of headaches.


📚 Extra Reading & References

Challenge

Challenge

You are building a product detail page for a Remix e-commerce site. The route for this page is dynamic, defined as app/routes/products.$productId.tsx.

Your task is to implement both the server-side data loader and the client-side component to fetch and display product information. The loader must handle dynamic URL parameters, optional URL search parameters, and potential errors.

Part 1: The loader function

  1. Export an async function named loader. This function should accept the standard LoaderFunctionArgs which include params and request.
  2. Inside the loader, extract the productId from the params object.
  3. Use the mockProducts array to find the corresponding product. If no product with the given productId exists, you must throw a new Response("Product Not Found", { status: 404 }).
  4. Extract an optional URL search parameter named variant from the request object's URL.
  5. Return the found product object and the extracted variant (selectedVariant) using the json helper function. The selectedVariant should be null if the query parameter is not present.

Part 2: The Component

  1. Define and export a default React component named ProductPage.
  2. Inside the component, use the useLoaderData hook to access the data returned from your loader. You must use TypeScript to ensure end-to-end type safety by correctly typing the hook with your loader's type (useLoaderData<typeof loader>()).
  3. Render the product's name in an <h1> tag.
  4. If a selectedVariant exists in the data, render it inside a <p> tag with the text Selected Variant: [variant]. Otherwise, render nothing for the variant.

Expected result

The final code should correctly implement a loader function and a React component.

Loader Implementation:

  • The loader function is exported and correctly typed with LoaderFunctionArgs.
  • It correctly deconstructs params to get the productId.
  • It uses request.url to create a URL object and get the variant search parameter.
  • It finds the product in mockProducts or throws a new Response with a 404 status if not found.
  • It returns a json response containing { product, selectedVariant }.

Component Implementation:

  • A default exported component ProductPage is created.
  • Inside the component, useLoaderData<typeof loader>() is called to get the data in a type-safe manner.
  • The component's JSX renders an <h1> with the product.name.
  • It conditionally renders a <p> tag with the selectedVariant only if it's not null.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.