A First Look at Remix.run
Tags: webdev, javascript, react, node
Published: 2020-10-28 22:59:58

---
title: A First Look at Remix.run
published: true
description: An overview of Remix, a new hybrid React framework.
tags: webdev, javascript, react, node
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/6bkwrfbwxkb3cq1oo7r4.jpg
---

Today the [Remix Run](https://remix.run/) Supporter Preview finally launched. Remix is a new React framework.

One of the thing that excites me the most about Remix is the team behind it. [Michael Jackson](https://twitter.com/mjackson) and [Ryan Florence](https://twitter.com/ryanflorence) are some of the most knowledgeable engineers in the React community and have built a lot of things (like [React Router](https://reactrouter.com/), [UNPKG](https://unpkg.com/) and [Reach UI](https://reach.tech/)) that I have used countless times in my career personally, at AWS, and when working with customers when I was consulting.

Another thing that excites me is the innovation that has happened over the past few years since React was first released and how they have built upon those ideas in Remix.

In this quick post I'll show you how Remix works:

1. Creating a new project
2. Setting credentials
3. Configuring routing
4. Adding dynamic routing
5. Dynamic data fetching
6. Dynamic data fetching using route parameters
7. Using the global Remix config

> You can also check out my video walkthrough of how Remix works [here](https://www.youtube.com/watch?v=HwdAK9FNUOE) 

## About Remix

### Pricing

Remix is not free. To use Remix, you need to buy either a indie ($250 per year) or enterprise ($1,000 per year) license. There are a lot of opinions about this. I think there's a good argument on both sides, so here's mine.

I've personally paid more than $250 for 1 hour of training when I was getting into consulting, so for an entire year of support from a team I can trust for a framework that makes it easier for me to build apps – I think it's worth it. You might also look at frameworks like Next.js that are free and decide it's not worth it. Both opinions are totally valid IMO.

At the end of the day I just want to be able to build high quality apps and do so as quickly and efficiently as possible without compromising quality, and because time is money I often invest in tools that can make me better and faster (especially those where I can leverage my existing skillset).

### SSR

The entire idea behind Remix is that everything is SSR. It also has a lot lower level of an API than something like Next.js, exposing the entire Request object and allowing you to modify things like headers before rendering the page. I still don't know all of it's capabilities, but at first glance I see it as a closer to the metal / more configurable version of Next.js but without SSG, and there are some benefits to nested routes that I honestly haven't quite explored yet, but it feels interesting.

### Routing

One other large difference between Remix and other frameworks (like Next.js) is how the routing works. Nested routes and params are supported in Remix, and "are a critical idea to understand in Remix" (according to the docs).

Using an `Outlet` from React Router Dom, you can build out a hierarchy of nested routes with a pretty simple to use API:

```js
import React from "react";
import { Link, Outlet } from "react-router-dom";
import { useRouteData } from "@remix-run/react";

export default function Team() {
  let data = useRouteData();
  return (
    <div>
      <h2>Team</h2>
      <ul>
        {data.map((member) => (
          <li key={member.id}>
            <Link to={member.login}>{member.login}</Link>
          </li>
        ))}
      </ul>
      <hr />
      <Outlet />
    </div>
  );
}
```

When you navigate using a `Link`, the Outlet will render the new content from the navigated route.

### HTTP Caching

Remix has this idea of __loaders__ that enable you to not just return data for a route, but send full responses, which includes sending cache control headers. By having simple apis to set headers for loaders and routes, you can easily take advantage of browsers (and CDNs) built in cache capabilities).

For instance, if you set cache headers on your responses, when the user visits the same route, it wont' even fetch the data, it'll use the cache. And if you put a CDN in front of your server, the server will rarely actually handle the requests because the CDN will have it cached

## Code

Enough of the explanation, let's look at some code.

### Creating a project

When you purchase a subscription for a Remix license you are given access to their dashboard. In this dashboard, you can view your license details, documentation, and billing information.

![Remix Dashboard](https://dev-to-uploads.s3.amazonaws.com/i/erf7n1rzd1op1n5kc68b.png)

This is a much different experience than most frameworks I've used that are simply open source, while this is all hidden behind the paywall.

From this dashboard you have everything you need to get going, including a quick start tutorial.

To get started, they recommend you clone an [open source starter project](https://github.com/remix-run/starter-express) that uses express as the server:

```js
$ git clone git@github.com:remix-run/starter-express.git my-remix-app
```

Out of the box they support Firebase to deploy using a single command:

```sh
firebase deploy
```

In the future they plan to support deployment to these different cloud service providers as well:

- Firebase
- Vercel
- AWS Amplify
- Architect
- Azure
- Netlify

### Restricting access

You may be wondering how they limit access to only paying customers. The way they do this is that, to install the latest `node-modules` necessary for the app to run, you have to configure an __.npmrc__ file that looks something like this to include your secret key:

```
//npm.remix.run/:_authToken=your-unique-token

# This line tells npm where to find @remix-run packages.
@remix-run:registry=https://npm.remix.run
```

Once this is configured you can install the dependencies using npm or yarn.

### Project structure

Here is a look at the Remix-specific project configuration

```
remix-app  
└───app
│   │   App.tsx
│   │   entry-browser.tsx
│   │   entry-server.tsx
│   │   global.css
│   │   tsconfig.json
│   └───routes
│       │   index.js
│       │   404.js
│       │   500.js
│       │   index.css
└───config
│   │   shared-tsconfig.json
└───loaders
│    │   global.ts
│    │   tsconfig.json
│
└───public
│    │   favicon.ico
│    
└───.npmrc
│
└───remix.config.js
│
└───server.js
```

The entry-point is __App.tsx__, and looks something like this:

```js
import React from "react";
import { Meta, Scripts, Styles, Routes, useGlobalData } from "@remix-run/react";

export default function App() {
  let data = useGlobalData();

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <Meta />
        <Styles />
      </head>
      <body>
        <Routes />
        <Scripts />
        <footer>
          <p>This page was rendered at {data.date.toLocaleString()}</p>
        </footer>
      </body>
    </html>
  );
}
```

One interesting thing is this line:

```js
let data = useGlobalData();
```

In __loaders/global.ts__ you can configure global values, variables (both static and dynamic), or anything you need to load from the server in order to render your base layout. For instance, let's say we wanted to define the app version here and use it throughout our app, we can define this here:

```ts
import type { DataLoader } from "@remix-run/core";

let loader: DataLoader = async () => {
  return {
    date: new Date(),
    version: "V2.0"
  };
};

export = loader;
```

And then use it like this:

```js
let data = useGlobalData();
const version = data.version;
```

### Routing

> __From the docs:__ Routes in remix can be defined two ways: conventionally inside of the "app/routes" folder or manually with remix.config.routes.

So if I create a file called __routes/contact.js__, it will be it will be available at __http://myapp/contact__.

As mentioned though, you can also define them in __remix.config.js__.

From the code comments in __remix.config.js__:

```js
A hook for defining custom routes based on your own file
conventions. This is not required, but may be useful if
you have custom/advanced routing requirements.
```

Here's the example provided by the boilerplate:

```js
routes(defineRoutes) {
  return defineRoutes(route => {
    route(
      // The URL path for this route.
      "/pages/one",
      // The path to this route's component file, relative to `appDirectory`.
      "pages/one.tsx",
      // Options:
      {
        // The path to this route's data loader, relative to `loadersDirectory`.
        loader: "...",
        // The path to this route's styles file, relative to `appDirectory`.
        styles: "..."
      }
    );
  });
},
```

In doing this, you can define custom route configurations if you want or need to bypass the opinions of Remix.

### Data loading

One of the most interesting and powerful things about Remix is how it loads data.

The approach combines __routes__ with __loaders__ to enable dynamic data fetching.

> __From the docs:__ Page data in Remix comes from files called "route data loaders". These loaders are only ever run server side so you can use whatever node modules you need to load data, including a direct connection to your database.

If you name a loader the same as a route, Remix will automatically call it _before_ rendering, and make that data available in your route.

Let's take a look at how this works.

Let's say I create a route and page at __routes/people.ts__ that looks something like this:

```js
// routes/people.ts
import React, { useState, useEffect } from "react";

export default function People() {
  return (
    <div>
      <h2>Star Wars Characters</h2>
      // todo, fetch & map over star wars characters from API
    </div>
  );
}
```

When this route is rendered, I want to fetch the data for the array of people and make it available in the component.

To do this, we can create a new file in the __loaders/routes__ directory called __people.ts__ with the following code:

```js
// loaders/routes/people.ts
module.exports = () => {
  return fetch(`https://swapi.dev/api/people/`);
};
```

You can now use the `useRouteData` API from Remix to get access to this data in the route:

```js
// routes/people.ts
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useRouteData } from "@remix-run/react";

export default function People() {
  const data = useRouteData()
  return (
    <div>
      <h2>Star Wars Characters</h2>
      {
        data.results.map((result, index) => (
          <div key={index}>
            <Link to={`/person/${index + 1}`}>
              <h1>{result.name}</h1>            
            </Link>
          </div>
        ))
      }
    </div>
  );
}
```

#### The big question

Why didn't we have to await the fetch and then await the res.json? Because Remix awaits your loader, and fetch resolves to response, and Remix is expecting exactly that type of object.

> __From the docs:__ You might be scratching your head at that last bit. Why didn't we have to unwrap the fetch response with the usual await res.json()?

> If you've been around the Node.js world for a while you'll recognize that there are many different versions of "request" and "response". The express API req, res is probably the most ubiquitous, but wherever you go it's always a little different.

> When browsers shipped the Fetch API, they didn't just create a spec for window.fetch, but they also created a spec for what a fetch sends and returns, Request, Headers, and Response. You can read about these APIs on MDN.

> Instead of coming up with our own API, we built Remix on top of the Web Fetch API.

#### Adding caching

Let's have a look at how me might implement the caching mechanism I mentioned at the start of this post.

We can make the following update:

```js
const { json } = require("@remix-run/loader");
let res = await fetch(swapi);
let data = await res.json();
return json(data, { headers: { "cache-control": "max-age=3600"}})
```

For the next hour, the browser won't request that resource again, and for the next visitors, the CDN won't either.

### Combining dynamic routes, route params, and data fetching

How does this work for Dynamic routes? For example, what if I want to drill down into a route like __/person/#person-id__ and fetch the data?

Here's how that works. We need two new files: One for the route and one for the loader.

First, we'd create a loader at __loaders/person/$id.js__ that looks something like this:

```js
// loaders/person/$id.js
module.exports = ({ params }) => {
  return fetch(`https://swapi.dev/api/people/${params.id}`)
};
```

Next we'd create the route, something like __routes/person/$id.js__. Remix will parse the params from the url (the $id portion of person/$id) and passes them to the loader.

```js
// routes/person/$id.js
import React from "react";
import { useRouteData } from "@remix-run/react";

export default function Person() {
  const user = useRouteData()
  return (
    <div>
      <h2>{user.name}</h2>
      <h3>Homeworld - { user.homeworld }</h3>
      <p>Height - {user.height}</p>
    </div>
  );
}
```

The data fetched from the API will now be available using `useRouteData`.

### Up and Running with Remix.run video

{% youtube HwdAK9FNUOE %}

## Conclusion

Overall I'm really enjoying using Remix. It's an entirely new approach to building hybrid React web applications that is built upon the advancements we've seen in both modern and legacy web technologies over the years.

I expect to see Remix continue to get better over time, but am unsure how far or fast it will take off considering it is not OSS.

I applaud Ryan and Michael for trying a new payment model, and look forward to seeing how it turns out. The challenge of monetizing OSS has not completely been solved yet, so any new approaches in doing so lay the foundation for anyone looking to make their open source work profitable and maintainable now and in the future.

Also check out my post going a little deeper into the differences between Remix and Next.js.

{% link https://dev.to/dabit3/how-is-remix-different-from-next-js-4jd1 %}