Remix Flat Routes – An Evolution in Routing

This talk introduces the new Flat Routes convention that will most likely be the default in a future version of Remix. It simplifies the existing convention as well as gives you new capabilities.

Rate this content
Bookmark
Video Summary and Transcription
The video explores Remix Flat Routes, a new routing convention designed to simplify route management in Remix applications. Remix Flat Routes reduces the complexity of file systems by using filenames with dots to separate URL segments, unlike the typical nested folder structure in Remix routing. This approach enhances route visibility and supports co-location of support files, such as CSS and components, within route folders. The video also delves into the differences between Remix and Next.js, highlighting how Remix Flat Routes simplifies migration from other frameworks. Additionally, it offers insights into the benefits of using flat file and flat folder configurations for easier refactoring and redesign. The migration tool provided by Remix Flat Routes facilitates the transition to this new structure, ensuring routes maintain their hierarchy while altering file names and sorting as needed.

This talk has been presented at Remix Conf Europe 2022, check out the latest edition of this React Conference.

FAQ

To migrate an existing app to use Remix FlatRoutes, you can use the included migration tool by running the command 'mpx migrate-flat-routes' and specifying the source and target folders. This tool helps reorganize the routes into the new flat file or flat folder structure.

Yes, Remix FlatRoutes can handle route configurations from multiple directories. You can specify an array of paths to the routes folder in the Remix config, and FlatRoutes will automatically merge them into a single namespace, simplifying the management of routes across different backends or sections.

In the Flat Folders convention of Remix, each route's folder acts as a namespace where supporting files like CSS, components, and images can be co-located. This allows for relative imports within the route file, simplifying the development and maintenance of the application.

Unlike the typical nested folder structure in Remix, FlatRoutes uses a flat file system where all routes are defined in filenames using dots to separate URL segments. This approach decreases the complexity of the file system and makes the routes easier to manage and refactor.

In Remix FlatRoutes, a single underscore prefix is used for pathless layouts, and a dot is used instead of a slash to separate URL segments. To specify that a segment is not a layout, an underscore suffix is used, indicating the absence of an outlet.

The main benefits include better visibility of route structures, co-location of support files such as CSS and components with routes, reduced friction during refactoring and redesign, and easier migration from other frameworks.

Remix FlatRoutes is a new routing convention introduced to simplify the file structure in the Remix framework by eliminating nested folders and allowing easier refactoring and redesign. It was initially introduced as a separate NPM package and is expected to be integrated into future versions of Remix.

1. Introduction to Remix Flat Routes#

Short description:

Hi, I'm Michael Porter. I'll be speaking at RemixConf Europe on Remix Flat Routes and Evolution in Routing. I'll start with a brief introduction to the current routing convention. Remix uses folders to determine the parent layout, while Next.js requires a folder for every segment of the route. Next.js also uses separate files for named exports, leading to a large number of files. However, Next.js allows co-locating supporting files in the route folder.

Hi, I'm Michael Porter. You may know me online as Killamon, which is short for Killamonjaro. I've been a big fan of volcanoes for a long time. I'm excited to be speaking to you today at RemixConf Europe. My presentation will be on Remix Flat Routes and Evolution in Routing.

First, I'll start by giving a brief introduction on the current routing convention as we know it today. Here is a typical routing structure. It consists of a pathless layout for public pages, like the about page, a user section with its own layout which has a list view, a user detail view, as well as an edit page. Remix uses folders to determine the parent layout. It is expected that the parent layout will include an outlet to render its children. In this example, there is no user ID folder because we want the edit page to use the same user's layout as the other routes. Since the edit page is not nested, we use the dot for flat layout instead of the nested layout. When you create a nested layout, Remix requires you to create a folder for its children, plus a file for the layout itself. Unfortunately, one of the drawbacks of this convention is that the folder in a layout file ends up separated in your editor, since folders are typically displayed first. This can be annoying, especially on large applications with many routes.

As you know, Next.js recently introduced their own take on nested layouts. Let's compare their convention with Remix. Here is the same routing structure as the previous example. Next.js uses parentheses for pathless layouts, similar to Remix's double underscore prefix. The one thing you'll notice is that Next.js requires a folder for every segment of the route. The leaf route is a file named page. If a route segment adds a layout, you create a layout file. With Next., layouts and pages are separate things, whereas Remix doesn't differentiate. Again, looking back at our user edit route, Next.js looks for the closest layout, which is user slash layout. Another major difference with Remix is that Remix uses named exports for things like meta, links, headers, error boundary, etcetera. And Next.js uses separate files for each. This can result in a large number of files, depending on your app's needs. It led one person on Twitter to tweet this screenshot. Granted, this is an extreme example. One of the benefits of a folder for each route, though, is that Next.js does let you co-locate supporting files in the route folder.

2. Introduction to Remix FlatRoutes#

Short description:

Remix FlatRoutes is a new convention that aims to make it easier to see and organize the routes in your app. It allows for the co-location of support files with routes, decreases refactor and redesign friction, and helps apps migrate to Remix. FlatRoutes were first introduced by Brian Florence and have since been implemented as a separate package. To add it to your app, simply npm install dash d RemixFlatRoutes.

Things like CSS, components, images, etcetera. This is one of the main things Remix devs have been asking for. We'll discuss how Remix FlatRoutes supports this shortly.

Now that we have that out of the way, let's discuss the new Remix FlatRoutes convention. It's currently a separate MPM package, but will be included in a future version of Remix as core functionality.

So what are the goals of the Remix FlatRoutes? Make it easier to see the route your app is designed. Just pop open the Routes folder, and they're all right there. Since the file system typically sorts folders first, when you have dozens of routes, it's hard to see which folders have layouts and which don't today. Now all related routes are sorted together. Allow co-location of support files with routes. You'll see how you can keep your styles, components, and other supporting files with your routes. Decrease refactor and redesign friction. While code editors are pretty good at fixing up imports when you move files around, and Remix does have the tilde import alias, it's just generally easier to refactor code base that doesn't have a bunch of nested folders. Remix will no longer require this. Additionally, when redesigning the user interface, it's simpler to adjust the names of the files rather than creating and deleting folders and moving routes around to change the way they nest. And finally, help apps migrate to Remix. Existing apps typically don't have a nested routes folder structure like today's conventions. Moving to Remix is arduous because you have to deal with all of the imports. Also, as we saw with Next's new nested layouts, FlatRoutes make it easier to migrate from other frameworks to Remix.

So Remix FlatRoutes was first introduced as a gist by Brian Florence back on April 7th of this year. He posted the link on the Remix board, and I just happened to see it. And I was intrigued because I, too, was looking to simplify my routing structure. Less than two weeks later, I made the first commit implementing the FlatRoutes spec. The trickiest part was trying to figure out how to determine the parent layout when there were no folders. Simply a dot separated file name. We'll discuss how that was implemented in a little while. An interesting point is that it wasn't until a month later that Next.js posted the first layouts RFC, describing their new nested layouts convention, which is now available as an experimental feature in Next.js 13. As I mentioned before, Remix FlatRoutes is currently implemented as a separate package. To add it to your app, simply npm install dash d RemixFlatRoutes. Since routes are determined at build time, this is a dev dependency and is not needed at run time.

3. Customizing Remix Routes#

Short description:

One of the things about Remix is that although it's opinionated, it does have some escape hatches that let you add your own customizations. In this case, it's the routes configuration where you can add your own routes in addition to the default convention. RemixFlatRoutes changes some of the file naming conventions that we're used to. For example, for pathless layouts, use a single underscore instead of a double underscore prefix. Instead of using folders for routes, the filename includes the entire route, so use the dot instead of slash to separate URL segments. Remix FlatRoute supports two configurations, flat files and flat folders. Flat files will typically be used for simpler apps as everything is in the filename and there are no folders. Although Flat File simplifies the routing convention considerably, it does so with some drawbacks. There are no folders.

One of the things about Remix is that although it's opinionated, it does have some escape hatches that let you add your own customizations. In this case, it's the routes configuration where you can add your own routes in addition to the default convention.

Since Remix assumes the files in the routes folder use the default convention, you'll need to tell Remix to ignore all files in the routes folder. Finally, call the FlatRoutes function to scan the folder using the new FlatRoutes convention. In the future, you'll be able to specify which convention you want to use directly through the Remix config file.

RemixFlatRoutes changes some of the file naming conventions that we're used to. For example, for pathless layouts, use a single underscore instead of a double underscore prefix. The params prefix remains the same, the dollar sign, but I'll show you how we can change that later. Instead of using folders for routes, the filename includes the entire route, so use the dot instead of slash to separate URL segments. And finally, to handle scenarios like our user edit route, the underscore suffix specifies the segment is not a layout because it has no outlet. I'll demonstrate this later.

Remix FlatRoute supports two configurations, flat files and flat folders. Flat files will typically be used for simpler apps as everything is in the filename and there are no folders. Here is the same example we used before, but using the flat files convention. Notice that there are no folders. The entire URL structure is visible at a glance without having to drill down into separate folders. We still have to identify the index route, in this case, users slash index. Notice how we named the file users dot index. The leading underscore here is simply to sort the index route before the other child routes.

As I mentioned, we are using dots instead of folders to separate the paths. But without folders, how does Remix know what the parent layout is? To determine the parent layout, Remix Flat Routes finds the longest matching prefix, and that determines the parent layout. Here we see that public prefix of public dot about matches the public TSX layout. Same with users. Remember in the previous example, where we didn't want the edit route to nest under user ID? There, we used dots in the file name to deal with it. But how do you deal with that when everything uses dots? Remix Flat Route allows you to use a trailing underscore on a parent route to specify that this is not a layout. As you can see in the edit route, the user ID should not be treated as a parent layout, hence the underscore. This ensures that users that user ID prefix is not matched with that route. And Remix will then look to the next segment for a matching layout, which is the users layout.

Although Flat File simplifies the routing convention considerably, it does so with some drawbacks. There are no folders.

4. Flat Folders Convention and Co-location#

Short description:

We cannot co-locate supporting files with our routes. Flat folders look just like Flat Files. The main difference is that instead of the routing being a simple file name, the folder itself is the route name. Remix doesn't differentiate between routes and layouts. Remix supports multiple aliases for the route file. One of the main benefits of the Flat Folders convention is to support co-location. Your route file will now let you import these assets as a relative import. I've been experimenting with splitting my route file into a route and a route server file.

We cannot co-locate supporting files with our routes. Even if we were to add rules to ignore these other files, it would require you to import them with the full path, not exactly simplifying things. Flat folders look just like Flat Files. The main difference is that instead of the routing being a simple file name, the folder itself is the route name. The route file, index.tsx, is located inside the folder. This is similar to the Next.js page file.

Remix doesn't differentiate between routes and layouts. Again, layouts are simply routes with outlets. So, index.tsx or layout.tsx mean the same thing. They are simply aliases and are mainly used to be more descriptive when looking at your routes. Remix supports multiple aliases for the route file. You can use either index, route, layout, or page, as well as add the underscore prefix. This helps sort route and layout files to the top of the file list when co-locating files.

As we stated before, one of the main benefits of the Flat Folders convention is to support co-location. Here we are co-locating support files like CSS, components, server files, images, etc. Your route file will now let you import these assets as a relative import. I've been experimenting with splitting my route file into a route and a route server file. The main reason is that I use Zod for validation, and the package is kind of heavy. By only defining and using the Zod schema in the server file, I guarantee that Zod does not end up in the client bundle.

5. Migrating Existing Apps to Flat Routes#

Short description:

To migrate your existing app to Flat Routes, use the Remix Flat Routes package's migration tool. Specify the source and target folders, ensuring they are different. Choose between flat files or flat folders. Verify the migration by comparing the routes before and after using the mpx-remix-routes command. The routes should have the same hierarchy and paths, with only the file names and sorting potentially changing.

So now that we've seen the benefits of Flat Routes, how do we migrate our existing app? The Remix Flat Routes package includes a migration tool. Simply run the command mpx migrate-flat-routes and specify the source and target folders. The folders must be different to prevent the tool from overwriting your original routes. You can specify whether you want flat files or flat folders. Here's a screenshot of the routes from the sample Fakebooks app before and after migration. You can see that it lets you quickly see how your routes are structured without having to expand the folders. One way to verify that the migration went smoothly is to run the mpx-remix-routes command on the original routes as well as the migrated routes. Since remix-flat-routes creates the same route configuration that was generated by the default convention, the routes should be identical both in hierarchy and paths. The only differences are the file names, and maybe some sorting.

Michael Carter
Michael Carter
16 min
18 Nov, 2022

Comments

Sign in or register to post your comment.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a web framework built on React Router that focuses on web fundamentals, accessibility, performance, and flexibility. It delivers real HTML and SEO benefits, and allows for automatic updating of meta tags and styles. It provides features like login functionality, session management, and error handling. Remix is a server-rendered framework that can enhance sites with JavaScript but doesn't require it for basic functionality. It aims to create quality HTML-driven documents and is flexible for use with different web technologies and stacks.
Don't Solve Problems, Eliminate Them
React Advanced 2021React Advanced 2021
39 min
Don't Solve Problems, Eliminate Them
Top Content
Kent C. Dodds discusses the concept of problem elimination rather than just problem-solving. He introduces the idea of a problem tree and the importance of avoiding creating solutions prematurely. Kent uses examples like Tesla's electric engine and Remix framework to illustrate the benefits of problem elimination. He emphasizes the value of trade-offs and taking the easier path, as well as the need to constantly re-evaluate and change approaches to eliminate problems.
Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
How React Router Became a Framework
React Advanced 2024React Advanced 2024
31 min
How React Router Became a Framework
My name is Mark Dalglish and I'm here to discuss how ReactRouter became a framework. Remix is built on ReactRouter and heavily relies on it. Remix feels like a framework because it has a CLI, manages the dev and build lifecycle, and has strong opinions about the file system structure. Remix embraced Vite as a plugin, allowing developers to integrate it seamlessly into their existing Vite setup. The shift to Vite led to a change in the philosophy of Remix Vite, enabling frameworks to orchestrate all the environment builds and make the framework as a plugin pattern first class. React Router is merging with Remix to make all the build time framework features available to React Router consumers. React Router is now officially a framework as well as a library. The move to integrate Remix into React Router is driven by the exploration of the next generation of Remix. React Router V7 simplifies by dropping the React Native layer and allows flexibility for consumers to use it as a library or as a framework with additional architectural features provided by plugins. The focus is on betting on Vite in the long term, and React Router plans to support React Server components. Thank you to Mark for answering the questions.
How to Make a Web Game All by Yourself
JS GameDev Summit 2023JS GameDev Summit 2023
27 min
How to Make a Web Game All by Yourself
This talk guides you on how to make a web game by yourself, emphasizing the importance of focusing on tasks that interest you and outsourcing the rest. It suggests choosing a game engine that allows distribution on the web and aligns with your understanding and enjoyment. The talk also highlights the significance of finding fun in the creative process, managing scope, cutting features that don't align with the game's direction, and iterating to the finish line. It concludes by discussing the options for publishing the game on the web and leveraging unique web features.

Workshops on related topic

Remix Fundamentals
React Summit 2022React Summit 2022
136 min
Remix Fundamentals
Top Content
Featured WorkshopFree
Kent C. Dodds
Kent C. Dodds
Building modern web applications is riddled with complexity And that's only if you bother to deal with the problems
Tired of wiring up onSubmit to backend APIs and making sure your client-side cache stays up-to-date? Wouldn't it be cool to be able to use the global nature of CSS to your benefit, rather than find tools or conventions to avoid or work around it? And how would you like nested layouts with intelligent and performance optimized data management that just works™?
Remix solves some of these problems, and completely eliminates the rest. You don't even have to think about server cache management or global CSS namespace clashes. It's not that Remix has APIs to avoid these problems, they simply don't exist when you're using Remix. Oh, and you don't need that huge complex graphql client when you're using Remix. They've got you covered. Ready to build faster apps faster?
At the end of this workshop, you'll know how to:- Create Remix Routes- Style Remix applications- Load data in Remix loaders- Mutate data with forms and actions
Back to the Roots With Remix
React Summit 2023React Summit 2023
106 min
Back to the Roots With Remix
Featured Workshop
Alex Korzhikov
Pavlik Kiselev
2 authors
The modern web would be different without rich client-side applications supported by powerful frameworks: React, Angular, Vue, Lit, and many others. These frameworks rely on client-side JavaScript, which is their core. However, there are other approaches to rendering. One of them (quite old, by the way) is server-side rendering entirely without JavaScript. Let's find out if this is a good idea and how Remix can help us with it?
Prerequisites- Good understanding of JavaScript or TypeScript- It would help to have experience with React, Redux, Node.js and writing FrontEnd and BackEnd applications- Preinstall Node.js, npm- We prefer to use VSCode, but also cloud IDEs such as codesandbox (other IDEs are also ok)
How to Solve Real-World Problems with Remix
Remix Conf Europe 2022Remix Conf Europe 2022
195 min
How to Solve Real-World Problems with Remix
Featured Workshop
Michael Carter
Michael Carter
- Errors? How to render and log your server and client errorsa - When to return errors vs throwb - Setup logging service like Sentry, LogRocket, and Bugsnag- Forms? How to validate and handle multi-page formsa - Use zod to validate form data in your actionb - Step through multi-page forms without losing data- Stuck? How to patch bugs or missing features in Remix so you can move ona - Use patch-package to quickly fix your Remix installb - Show tool for managing multiple patches and cherry-pick open PRs- Users? How to handle multi-tenant apps with Prismaa - Determine tenant by host or by userb - Multiple database or single database/multiple schemasc - Ensures tenant data always separate from others
Integrating LangChain with JavaScript for Web Developers
React Summit 2024React Summit 2024
92 min
Integrating LangChain with JavaScript for Web Developers
Featured Workshop
Vivek Nayyar
Vivek Nayyar
Dive into the world of AI with our interactive workshop designed specifically for web developers. "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" offers a unique opportunity to bridge the gap between AI and web development. Despite the prominence of Python in AI development, the vast potential of JavaScript remains largely untapped. This workshop aims to change that.Throughout this hands-on session, participants will learn how to leverage LangChain—a tool designed to make large language models more accessible and useful—to build dynamic AI agents directly within JavaScript environments. This approach opens up new possibilities for enhancing web applications with intelligent features, from automated customer support to content generation and beyond.We'll start with the basics of LangChain and AI models, ensuring a solid foundation even for those new to AI. From there, we'll dive into practical exercises that demonstrate how to integrate these technologies into real-world JavaScript projects. Participants will work through examples, facing and overcoming the challenges of making AI work seamlessly on the web.This workshop is more than just a learning experience; it's a chance to be at the forefront of an emerging field. By the end, attendees will not only have gained valuable skills but also created AI-enhanced features they can take back to their projects or workplaces.Whether you're a seasoned web developer curious about AI or looking to expand your skillset into new and exciting areas, "Hands-On AI: Integrating LangChain with JavaScript for Web Developers" is your gateway to the future of web development. Join us to unlock the potential of AI in your web projects, making them smarter, more interactive, and more engaging for users.
Build and Launch a personal blog using Remix and Vercel
Remix Conf Europe 2022Remix Conf Europe 2022
156 min
Build and Launch a personal blog using Remix and Vercel
Featured Workshop
Robert Pop
Robert Pop
In this workshop we will learn how to build a personal blog from scratch using Remix, TailwindCSS. The blog will be hosted on Vercel and all the content will be dynamically served from a separate GitHub repository. We will be using HTTP Caching for the blog posts.
What we want to achieve at the end of the workshop is to have a list of our blog posts displayed on the deployed version of the website, the ability to filter them and to read them individually.
Table of contents: - Setup a Remix Project with a predefined stack- Install additional dependencies- Read content from GiHub- Display Content from GitHub- Parse the content and load it within our app using mdx-bundler- Create separate blog post page to have them displayed standalone- Add filters on the initial list of blog posts
Building High-Performance Online Stores with Shopify Hydrogen and Remix
React Advanced 2023React Advanced 2023
104 min
Building High-Performance Online Stores with Shopify Hydrogen and Remix
WorkshopFree
Alexandra Spalato
Alexandra Spalato
I. Introduction- Overview of Shopify Hydrogen and Remix- Importance of headless e-commerce and its impact on the industry
II. Setting up Shopify Hydrogen- Installing and setting up Hydrogen with Remix- Setting up the project structure and components
III. Creating Collections and Products- Creating collections and products using Hydrogen’s React components- Implementing a Shopping Cart- Building a shopping cart using Hydrogen’s built-in components
VI. Building the home page with Storyblok- Cloning the space and explaining how it works- Implementing Storyblok in the repo- Creating the Blok components- Creating the Shopify components- Implementing personalisation