What Remix Is and Where It Runs

Remix is a server-first JavaScript framework that builds on React for the front end and favors rendering applications on the edge. Its history goes back to 2019, when it was available only as a subscription-based premium framework; in 2021 the founders raised seed funding and open sourced it. Because the server-side code can run as serverless or edge functions, deployments are typically cheaper than a traditional server and sit closer to users. The creators describe Remix as a "center stack" framework, since it adapts the requests and responses exchanged between server and client to whichever platform it targets.

Deployment and the Compiler

Remix does not ship a server — you supply it — so it can run in any Node.js or Deno environment, including Netlify Edge and DigitalOcean's App Platform. Remix is itself a compiler: it translates requests for the target platform, using esbuild to generate server request handlers. Those HTTP handlers are built on the Web Fetch API and run on the server by adapting them to the deployment platform.

Stacks and Static Caching

Remix stacks are starter projects with common tooling preconfigured. Three official stacks are maintained by the Remix team, all named after musical genres, and community stacks exist as well — among them Netlify's K-Pop Stack, which bundles a Supabase database and authentication, Tailwind for styling, Cypress for end-to-end tests, Prettier, ESLint, and TypeScript.

Despite requiring a server, Remix can capture Jamstack-style benefits by caching routes. It does not perform typical SSG the way Next.js or Gatsby do; instead you set the standard Cache-Control HTTP header in a Remix headers function, either for a specific route or in root.tsx.

[[headers]]
  for = "/build/*"
  [headers.values]
    "Cache-Control" = "public, max-age=31536000, s-maxage=31536000"

The headers function is added wherever the caching is wanted. This example caches for one hour:

export function headers() {
  return {
    "Cache-Control": "public, s-maxage=360",
  };
};

Routing, Layouts and the Outlet

Remix routes come from the file system, as in several other frameworks, but the distinguishing feature is nested routing. Every app begins with root.tsx, which holds the document skeleton — <html>, <head>, and <body> with the components the app needs. The <Scripts> component there is what enables JavaScript on the site; some behavior works without it, but not all. root.tsx is the parent layout for everything under the routes directory, and route content renders where its <Outlet/> component appears.

Remix was founded by members of the React Router team and uses React Router itself. Nested routing means a nested route is a separate section of the same page rather than a new page, which keeps business logic confined to the files that need it. Errors can be localized to the failing section: other routes on the page remain usable, and the broken route can surface relevant error context without crashing the whole page.

Nesting is triggered when a root file in app/routes shares the name of a directory whose files load inside it. That root file becomes a layout, and its <Outlet /> marks where the nested routes render. The outlet belongs in the file at the root of app/routes that shares the nested routes' name — for example, code placed in app/routes/about.tsx provides the outlet for files in app/routes/about:

import { Outlet } from "@remix-run/react";

export default function About() {
  return (
    <>
      <section>
        I am the parent layout. I will be on any page inside of my named directory.
      </section>
      { /* All of my children, the files in the named directory, will go here. */ }
      <Outlet />
    </>
  )
}

Any file in app/routes/ becomes a route at the URL matching its name, and a directory can be added with an index.tsx file.

app/
├── routes/
│   │
│   └── blog
|   |   ├── index.tsx ## The /blog route
│   └── about.tsx  ## The /about route
│   ├── index.tsx  ## The / or home route
└── root.tsx

When a route shares its name with a directory, the named file acts as the layout and must include an Outlet component to position the nested route.

app/
├── routes/
│   │
│   └── about
│   │   ├── index.tsx
│   ├── about.tsx ## this is a layout for /about/index.tsx
│   ├── index.tsx
└── root.tsx

Layouts can also be created with a double-underscore (__) prefix.

app/
├── routes/
│   │
│   └── about
│   │   ├── index.tsx
│   ├── index.tsx
│   ├── about.tsx
│   ├── __blog.tsx ## this is also a layout
└── root.tsx

https://your-url.com/about still renders app/routes/about.tsx, but it also renders whatever app/routes/about/index.tsx contains at the point of the Outlet in that file's markup.

Dynamic Segments

A dynamic route varies by URL content — a blog post name or a customer id, for instance. The $ prefix on the route signals the dynamic segment; the rest of the name is arbitrary.

app/
├── routes/
│   │
│   └── about
│   │   ├── $id.tsx
│   │   ├── index.tsx
│   ├── about.tsx ## this is a layout for /about/index.tsx
│   ├── index.tsx
└── root.tsx

Data Loading on the Server

Because Remix renders data on the server, the client-side patterns common to React apps, such as useState() and useEffect() hooks, are rarely needed — client state has largely already been evaluated server-side. Fetching is independent of server type: Remix translates between request and response, so the standard Web Fetch API works. Fetching happens in a loader function that runs only on the server, and the component renders the result through the useLoaderData() hook. The example below pulls a random cat image from the Cat as a Service API.

import { Outlet, useLoaderData } from '@remix-run/react'

export async function loader() {
  const response = await fetch('<https://cataas.com/cat?json=true>')
  const data = await response.json()
  return {
    data
  }
}

export default function AboutLayout() {
  const cat = useLoaderData<typeof loader>()
  return (
    <>
      <img
        src={`https://cataas.com/cat/${cat}`}
        alt="A random cat."
      />
      <Outlet />
    </>
  )
}

Dynamic routes need the URL parameter to decide what to render; the loader function receives it through a params argument.

import { useLoaderData } from '@remix-run/react'
import type { LoaderArgs } from '@remix-run/node'

export async function loader({ params }: LoaderArgs) {
  return {
      params
  }
}

export default function AboutLayout() {
  const { params } = useLoaderData<typeof loader>()
  return <p>The url parameter is {params.tag}.</p>
}

Route Module Functions

The route module API supplies helper functions that extend ordinary HTML elements and attributes. Each route can define its own.

Handling form submissions

An action function adds behavior to a form action using the standard web FormData API.

export async function action({ request }) {
  const body = await request.formData();
  const todo = await fakeCreateTodo({
      title: body.get("title"),
  });
  return redirect(`/todos/${todo.id}`);
}

Headers

Any standard HTTP header can be returned from a headers function. Since every route can define headers, conflicts between nested routes are resolved by the deepest route — the URL with the most forward slashes (/) — winning. Headers can also be forwarded through actionHeaders, loaderHeaders, or parentHeaders.

export function headers({
  actionHeaders,
  loaderHeaders,
  parentHeaders,
}) {
  return {
"Cache-Control": loaderHeaders.get("Cache-Control"),
  };
}

Meta tags

The meta function sets the document's meta tags. One is defined in root.tsx by default, and each route can update it.

export function meta() {
  return {
    title: "Your page title",
    description: "A new description for each route.",
  };
};

HTML link elements in the document <head> import CSS and similar resources. The links function — distinct from the <Link /> component — lets routes import only what they need, so CSS files can be scoped to the routes that use them. It returns an array of objects, each either a HtmlLinkDescriptor from the link API or a PageLinkDescriptor that can prefetch a page's data.

export function links() {
  return [
    // add a favicon
    {
      rel: "icon",
      href: "/favicon.png",
      type: "image/png",
    },
    // add an external stylesheet
    {
      rel: "stylesheet",
      href: "<https://example.com/some/styles.css>",
      crossOrigin: "true",
    },
    // add a local stylesheet,
    { rel: "stylesheet", href: stylesHref },

    // prefetch a page's data
    { page: "/about/community" }
  ]
}

Client-side navigation

The <Link/> component moves between routes in the app. Use <Link to="">Name</Link> rather than <a href="">Name</a> to get client-side routing. Its prefetch prop accepts none (the default), intent to fetch data once Remix detects a hover or focus on the link, or render to fetch the route's data as soon as the link renders.

import { Link } from "@remix-run/react";

export default function Nav() {
  return (
    <nav>
      <Link to="/">Home</Link>{" "}
      <Link to="/about">About</Link>{" "}
      <Link to="/about/community" prefetch="intent">Community</Link>
    </nav>
  );
}

To put this knowledge to work, Remix offers a Jokes app and a Blog tutorial, and you can also start a new app from scratch or try the K-Pop Stack.