First look at Remix

By Dave Bitter

8 min read

There has been a lot of buzz around the open-source release of Remix. I took a first look by following the deep-dive tutorial and this is what I found.

First look at Remix
Authors

Remix is a full-stack web framework that lets you focus on the user interface and work back through web fundamentals to deliver a fast, slick, and resilient user experience. This is what excited me when I first read about Remix. I'm a big advocate for progressively enhancing web applications and this framework seems to take this approach by simply using web fundamentals.

This is not a step-by-step guide on how to make a web application with Remix, but rather some features I noticed and wanted to highlight. That might come later. If you are looking for that, Remix.run is an amazing landing page and contains very well written documentation that will take you through all the reasons why they build this framework, what it offers and how it works. Seriously, one of the best landing pages I've seen in the past few years. Please, have a read there and come back for my view as a Next.js fanboy.

Routing mechanism

Like Next.js, Remix uses a file-based routing system. In /app (where your app will live) you can create a folder called routes. Every file you add (e.g. /app/routes/example will create a route and page under http://website.com/example. If you're unfamiliar with this concept, please read my article on my personal blog A simple, yet detailed introduction to Next.js. Next.js and Remix work nearly the same with some exceptions like creating a dynamic page ([slug] vs. $slug. If this is not the way you want to work, you can also define your routes in an object for both of these frameworks.

Nested routes

Remix seems to heavily rely on the usage of nested routes as "partials". Let's say you are building an admin view. You might have multiple routes for several admin pages:


- app
  - routes
      - admin.tsx
      - admin
          - new.tsx
          - edit.tsx
              $user.tsx

All these admin pages might share a special navigation bar for logged in admins. Naturally, you could load a reusable component in the markup of all these pages, but that sounds more like a partial that you used to use back when building websites with templating languages like Pug or Handlebars. Remix allows you to just load the partial in app/routes/admin.tsx and add a Remix component called <Outlet /> . This component serves as a placeholder where a child route can be rendered. In this case, that would be the new and edit route. I really like this approach of templating out pages.

Scoped JS and CSS per nested route

These nested routes are not just useful as partials, but will allow Remix to also easily chunck-up your nested routes for JS and CSS bundles. Naturally, it knows what pieces to load as you load them per nested route. This makes these nested routes true small little routes and optimises the loading of resources.

This concept is fundamental to how Remix works. You can read more about nested routes here and CSS scoping with <Links /> here.

Server- and client-side code

We've seen great strides by Next.js to make it easy for developers to expose server-side functions right next to client-side code. You can read more about that in my article Next.js page generation. At a first glance, Remix has an evenly convenient, if not better solution. I feel like Remix takes it to the next level by fully focussing on not having to use client-side JS as a standard, but rather an afterthought.

Loaders

Many web applications need to fetch data. You can use loader functions in combination with a useLoaderData hook to set this up.


import type { LoaderFunction } from "remix";

import type { User } from "@prisma/client";

import { db } from "~/utils/db.server";


type LoaderData = { users: Array<User> };

export let loader: LoaderFunction = async () => {
const data: LoaderData = {
  users: await db.user.findMany()
};

return { data };
};


export default function Users() {
const data = useLoaderData<LoaderData>();

return (
  <ul>
    {data.map(user => (
      <li>{user.name}</li>
    ))}
  </ul>
);
}

There is quite some Typescript-specific code here, but in its essence there is an async function exported called loader. This function fetches some data and returns an object with data. Note that you can return multiple pieces of data from various sources here. You can now access all this data using the useLoaderData hook. An important aspect of this is that no client-side JS is needed here. You just want some data from your server-side function and then use it to render a list on the server to serve to the client.

Actions

So what about handling things like forms? I need to handle that on the client right? Well, not necessarily. Forms can easily be handled with a method attribute on the form element. Sure, you might want to make a fancy multi-step form, but this is where progressive enhancement pops up again. Just make a form with a method and let it post using the web standards. You then export an action function that will handle the posting of the form. Take a look at this code snippet of the Jokes app tutorial I followed in preparation for this article. You can find my full end result in this repository.

import type { ActionFunction } from 'remix'

import { redirect } from 'remix'

import { db } from '~/utils/db.server'

export const action: ActionFunction = async ({ request }) => {
  const form = await request.formData()
  const name = form.get('name')
  const content = form.get('content')
  // we do this type check to be extra sure and to make TypeScript happy
  // we'll explore validation next!
  if (typeof name !== 'string' || typeof content !== 'string') {
    throw new Error(`Form not submitted correctly.`)
  }

  const fields = { name, content }

  const joke = await db.joke.create({ data: fields })
  return redirect(`/jokes/${joke.id}`)
}

export default function NewJokeRoute() {
  return (
    <div>
      <p>Add your own hilarious joke</p>
      <form method="post">
        <div>
          <label>
            Name: <input type="text" name="name" />
          </label>
        </div>
        <div>
          <label>
            Content: <textarea name="content" />
          </label>
        </div>
        <div>
          <button type="submit" className="button">
            Add
          </button>
        </div>
      </form>
    </div>
  )
}

There is a basic form (with no client-side JS) that just posts on submit. The action function is then called where we can then get the form data and handle it like normal. But what about validation? Naturally, you want to do this on the server, but it's considered good practice to do this on the client as well. The nice thing about having everything in this file is that we can reuse the same validation function in both places. Here's another snippet with just server-side validation implemented.


import type { ActionFunction, LoaderFunction } from "remix";

import {
  useActionData,
  redirect,
  Form
} from "remix";

import { JokeDisplay } from "~/components/joke";

import { db } from "~/utils/db.server";

import {
  requireUserId,
  getUserId
} from "~/utils/session.server";


export const loader: LoaderFunction = async ({
  request
}) => {
  const userId = await getUserId(request);
  if (!userId) {
      throw new Response("Unauthorized", { status: 401 });
  }
  return {};
};


function validateJokeContent(content: string) {
  if (content.length < 10) {
      return `That joke is too short`;
  }
}


function validateJokeName(name: string) {
  if (name.length < 2) {
      return `That joke's name is too short`;
  }
}


type ActionData = {
  formError?: string;
  fieldErrors?: {
      name: string | undefined;
      content: string | undefined;
  };
  fields?: {
      name: string;
      content: string;
  };
};


export const action: ActionFunction = async ({
  request
}): Promise<Response | ActionData> => {
  const userId = await requireUserId(request);
  const form = await request.formData();
  const name = form.get("name");
  const content = form.get("content");
  if (
      typeof name !== "string" ||
      typeof content !== "string"
  ) {
      return { formError: `Form not submitted correctly.` };
  }


  const fieldErrors = {
      name: validateJokeName(name),
      content: validateJokeContent(content)
  };
  const fields = { name, content };
  if (Object.values(fieldErrors).some(Boolean)) {
      return { fieldErrors, fields };
  }


  const joke = await db.joke.create({
      data: { ...fields, jokesterId: userId }
  });
  return redirect(`/jokes/${joke.id}`);
};


export default function NewJokeRoute() {
  const actionData = useActionData<
      ActionData | undefined
  >();


  return (
      <div>
          <p>Add your own hilarious joke</p>
          <Form method="post">
              <div>
                  <label>
                      Name:{" "}
                      <input
                          type="text"
                          defaultValue={actionData?.fields?.name}
                          name="name"
                          aria-invalid={
                              Boolean(actionData?.fieldErrors?.name) ||
                              undefined
                          }
                          aria-describedby={
                              actionData?.fieldErrors?.name
                                  ? "name-error"
                                  : undefined
                          }
                      />
                  </label>
                  {actionData?.fieldErrors?.name ? (
                      <p
                          className="form-validation-error"
                          role="alert"
                          id="name-error"
                      >
                          {actionData.fieldErrors.name}
                      </p>
                  ) : null}
              </div>
              <div>
                  <label>
                      Content:{" "}
                      <textarea
                          defaultValue={actionData?.fields?.content}
                          name="content"
                          aria-invalid={
                              Boolean(actionData?.fieldErrors?.content) ||
                              undefined
                          }
                          aria-describedby={
                              actionData?.fieldErrors?.content
                                  ? "content-error"
                                  : undefined
                          }
                      />
                  </label>
                  {actionData?.fieldErrors?.content ? (
                      <p
                          className="form-validation-error"
                          role="alert"
                          id="content-error"
                      >
                          {actionData.fieldErrors.content}
                      </p>
                  ) : null}
              </div>
              <div>
                  <button type="submit" className="button">
                      Add
                  </button>
              </div>
          </Form>
      </div>
  );
}

Note that we return the validation messages if there is something wrong and render the page again accessing them with the useActionData hook. If the form validates fine, we can redirect to the overview page.

This is a great example of how easy it can be to create an interactive part of your web application without the need for client-side JS for something that has web standards. Sure you can, but Remix is built in a way where you take this approach first.

Resource routes

If I had built the previous form without any client-side JS in Next.js, I would've had to build a Next.js API route. These are incredibly powerful. With Remix, you can do exactly the same, but even more. Remix doesn't just offer this for, for instance, JSON responses, but for any kind of response really. You can create a file with a special naming pattern like /app/routes/jokes[.]rss.tsx. The [.]rss part tells Remix that you will return a .rss file. In this code snippet, you can see how something like this could work.

import type { LoaderFunction } from 'remix'

import { db } from '~/utils/db.server'

export const loader: LoaderFunction = async ({ request }) => {
  const jokes = await db.joke.findMany({
    take: 100,
    orderBy: { createdAt: 'desc' },
    include: { jokester: { select: { username: true } } },
  })

  const host = request.headers.get('X-Forwarded-Host') ?? request.headers.get('host')
  if (!host) {
    throw new Error('Could not determine domain URL.')
  }
  const protocol = host.includes('localhost') ? 'http' : 'https'
  const domain = `${protocol}://${host}`
  const jokesUrl = `${domain}/jokes`

  const rssString = `
  <rss xmlns:blogChannel="${jokesUrl}" version="2.0">
    <channel>
      <title>Remix Jokes</title>
      <link>${jokesUrl}</link>
      <description>Some funny jokes</description>
      <language>en-us</language>
      <generator>Kody the Koala</generator>
      <ttl>40</ttl>
      ${jokes
        .map((joke) =>
          `
          <item>
            <title>${joke.name}</title>
            <description>A funny joke called ${joke.name}</description>
            <author>${joke.jokester.username}</author>
            <pubDate>${joke.createdAt}</pubDate>
            <link>${jokesUrl}/${joke.id}</link>
            <guid>${jokesUrl}/${joke.id}</guid>
          </item>
        `.trim()
        )
        .join('\n')}
    </channel>
  </rss>
`.trim()

  return new Response(rssString, {
    headers: {
      'Cache-Control': `public, max-age=${60 * 10}, s-maxage=${60 * 60 * 24}`,
      'Content-Type': 'application/xml',
      'Content-Length': String(Buffer.byteLength(rssString)),
    },
  })
}

How cool is that! The routes folder is not just for HTML pages, but you can create routes for any resource you need, hence the name resource routes.

Nested route utility exports

I found the utility exports that Remix offers on nested routes incredibly nice to use. Previously, I mentioned you could import CSS on nested routes and have it scoped and chuncked to just that nested route. There are a variety of other Remix utilities you can use scoped to a nested route.

SEO

You probably want to add some meta-tags to your pages. You can do this easily by exporting a MetaFunction on (nested) routes. Let's say you have some basic meta-tags on the root of the pages under app/root.tsx. You can export that function there like so:

export const meta: MetaFunction = () => {
  const description = `Learn Remix and laugh at the same time!`
  return {
    description,
    keywords: 'Remix,jokes',
    'twitter:image': 'https://remix-jokes.lol/social.png',
    'twitter:card': 'summary_large_image',
    'twitter:creator': '@remix_run',
    'twitter:site': '@remix_run',
    'twitter:title': 'Remix Jokes',
    'twitter:description': description,
  }
}

But you might want to update the title or description for a specific nested route. You guessed it, you can export the same function with different values there to extend this base set of meta tags. I think that's pretty sweet.

Error handling

You can export a CatchBoundary and ErrorBoundary function for every (nested) route.

export function CatchBoundary() {
  const caught = useCatch()

  if (caught.status === 404) {
    return <div className="error-container">There are no jokes to display.</div>
  }
  throw new Error(`Unexpected caught response with status: ${caught.status}`)
}

export function ErrorBoundary() {
  return <div className="error-container">I did a whoopsies.</div>
}

This will help you with two things. You can notify the user with some custom message on the page, but more importantly, you can isolate this error to just the nested route. The rest of you're application will run fine. This helps you think about how you want to handle your not so optimal flow.

Finally, loading some client-side JS for the first time

During the Jokes app tutorial, I didn't even realize that hadn't written any client-side JS yet. I think it's really cool that Remix doesn't load any client-side JS by default. Naturally, you might need some client-side JS so you can load the <Scripts /> component. This is the first time you will see JS files in your network tab. These optimised and chuncked files will be loaded and "hydrate" your application on the client.

Verdict.

I'm a big advocate of Progressive Enhancement to make web applications simple, accessible and resilient. I usually put this to practice for just components. Seeing Remix take this approach to the entire application gives me hope for a future of building great web applications using web standards and progressive enhancement.

For the first time in years, I felt like a "web developer" again instead of a JS engineer. It's incredible fun to start thinking about how to leverage these standards smartly. I'm very excited about what Remix will offer and will definitely continue researching Remix and sharing it with all of you. Thanks for reading!


Upcoming events

  • The Test Automation Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋‍♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Test Automation Meetup
  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋‍♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋‍♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design

Share