Learn Remix · 10/13

Advanced Routing Patterns

7 min read

Advanced Routing Patterns in Remix 🗺️

Welcome back! So you've got the basics of Remix routing down, and now you're ready to tackle some more complex scenarios. Think of this as moving from drawing straight lines to mastering curves and loops. These advanced patterns will give you the flexibility to build sophisticated, real-world applications. Let's dive in!

1. Pathless Layout Routes: Grouping UI Without Changing URLs 🖼️

The Problem:

Imagine you have a set of authentication pages like /login, /signup, and /forgot-password. You want them all to share a specific layout—perhaps a centered card on a colored background—that's different from the rest of your app. The straightforward way might be to create a folder like routes/auth and put your routes inside. But this would result in URLs like /auth/login, which isn't always what you want. You want the shared layout, but not the extra /auth in the URL.

The Solution: Pathless Layout Routes

Remix has a clever solution for this called "pathless layout routes." These routes allow you to group a set of routes under a shared layout component without affecting their URL structure.

To create a pathless layout route, you simply prefix the file or folder name with an underscore (_). For instance, you could create a file named routes/_auth.tsx. The leading underscore tells Remix that this route is for layout purposes only and should not add a path segment to the URL.

How it Works in Practice:

Let's set up our authentication pages with a shared layout.

  1. Create the Pathless Layout Route File:
    Inside your app/routes directory, create a new file called _auth.tsx. This file will contain the shared layout for your authentication routes.

    tsx
    // app/routes/_auth.tsx
    import { Outlet } from "@remix-run/react";
    
    export default function AuthLayout() {
      return (
        <div className="auth-container">
          <main>
            <Outlet />
          </main>
        </div>
      );
    }
  2. Create the Child Routes:
    Now, create the individual route files for login and signup, using a dot (.) to nest them under the _auth layout.

    • app/routes/_auth.login.tsx
    • app/routes/_auth.register.tsx
    tsx
    // app/routes/_auth.login.tsx
    export default function Login() {
      return <div>Login Form Here</div>;
    }
    tsx
    // app/routes/_auth.register.tsx
    export default function Register() {
      return <div>Register Form Here</div>;
    }

Now, when you navigate to /login or /register, you'll see the respective forms rendered within the AuthLayout, but the URLs remain clean and simple. It's like having a secret clubhouse for your auth pages that doesn't show up on the public map!

Alternatively, you can create a folder with a leading double underscore __ and place your layout and route files inside. For example, a folder named __auth would contain __auth.tsx, login.tsx, and register.tsx. This achieves the same outcome of shared layouts without altering the URL paths.

2. Splat Routes (Catch-all): Handling Unknown or Dynamic Deep Paths 📂

The Problem:

What if you're building a documentation site, a file browser, or a wiki where the URL structure can be deeply nested and isn't known ahead of time? For example, you might have URLs like /docs/getting-started/installation or /files/images/vacation/2024. Defining a route for every possible path would be a nightmare.

The Solution: Splat Routes

This is where "splat routes" come to the rescue. A splat route, also known as a catch-all route, will match the rest of a URL, including any slashes. This is incredibly useful for handling dynamic, deeply nested paths.

To create a splat route, you use a dollar sign ($) in the filename. For example, a file named routes/docs/$.tsx will match any URL that starts with /docs/.

Let's See it in Action:

Imagine we are building a simple file viewer.

  1. Create the Splat Route File:
    In your app/routes directory, create a file named files.$.tsx.

    tsx
    // app/routes/files.$.tsx
    import { useParams } from "@remix-run/react";
    
    export default function FileViewer() {
      const params = useParams();
      const filePath = params["*"]; // The splat parameter is available under the "*" key
    
      return (
        <div>
          <h1>Viewing File</h1>
          <p>Path: {filePath}</p>
        </div>
      );
    }

Now, any of the following URLs will be handled by this route:

  • /files/report.pdf
  • /files/images/profile.jpg
  • /files/projects/alpha/source/index.js

In each case, the part of the URL that comes after /files/ will be available in params["*"]. It’s like having a super-powered vacuum cleaner that sucks up the rest of the URL path for you to inspect.

3. Resource Routes: Building API Endpoints and Webhooks ⚙️

The Problem:

Sometimes you need to expose data or functionality from your server that isn't a user-facing page. This could be a JSON API for a mobile app, a way to dynamically generate a PDF, or a webhook endpoint for services like Stripe or GitHub to send you notifications. These aren't UI routes; they're data or action-oriented.

The Solution: Resource Routes

Remix makes it incredibly simple to create these server-only routes. A "resource route" is any route file that does not export a default component. Instead, it will typically export a loader function to handle GET requests and/or an action function to handle POST, PUT, PATCH, or DELETE requests.

Building a Simple API:

Let's create an API endpoint that returns a list of products.

  1. Create the Resource Route File:
    Create a file at app/routes/api.products.ts. The .ts extension indicates it's a TypeScript file without a React component.

    ts
    // app/routes/api.products.ts
    import { json } from "@remix-run/node";
    
    // This loader function handles GET requests to /api/products
    export const loader = async () => {
      const products = [
        { id: 1, name: "Laptop" },
        { id: 2, name: "Keyboard" },
      ];
    
      return json(products);
    };

And that's it! If you now make a GET request to /api/products, you'll receive a JSON response with the product data. No UI is rendered, just pure data. This is a fantastic way to build a full-fledged API right alongside your web application, sharing code and logic where it makes sense.

Important Note on Linking: When you link to a resource route from your UI (for example, to download a dynamically generated PDF), you should use the reloadDocument prop on the <Link> component or a standard <a> tag. This tells Remix to perform a full document request instead of trying to handle it as a client-side navigation.

4. File Uploads: Handling Multipart Forms in Action Functions 📤

The Problem:

Allowing users to upload files, like a profile picture or a document, is a common requirement. Handling multipart/form-data can be tricky, as it involves processing streams of data on the server.

The Solution: Remix's Form and Action Helpers

Remix provides tools to make file uploads more manageable within your action functions.

How it Works:

  1. The Form:
    In your component, you'll use a Remix <Form> with the encType prop set to "multipart/form-data" and the method as "post".

    tsx
    // In your component file
    import { Form } from "@remix-run/react";
    
    export default function ImageUploader() {
      return (
        <Form method="post" encType="multipart/form-data">
          <input type="file" name="my-image" />
          <button type="submit">Upload</button>
        </Form>
      );
    }
  2. The Action:
    In your route's action function, you can't just use request.formData() as that would load the entire file into memory, which is inefficient for large files. Instead, Remix provides unstable_parseMultipartFormData which allows you to process the file in a streaming fashion.

    Here's an example of how you might handle a file upload and save it to the local filesystem.

    ts
    // In your route file (e.g., app/routes/upload.tsx)
    import {
      json,
      unstable_createFileUploadHandler,
      unstable_parseMultipartFormData,
    } from "@remix-run/node";
    import type { ActionFunctionArgs } from "@remix-run/node";
    
    export const action = async ({ request }: ActionFunctionArgs) => {
      const uploadHandler = unstable_createFileUploadHandler({
        directory: "public/uploads",
        file: ({ filename }) => filename,
      });
    
      const formData = await unstable_parseMultipartFormData(request, uploadHandler);
    
      const file = formData.get("my-image");
    
      // Now you can do something with the file information
      // For example, save the file path to your database
    
      return json({ message: "File uploaded successfully!" });
    };

In this example, unstable_createFileUploadHandler creates a handler that streams the uploaded file directly to the public/uploads directory. This is much more memory-efficient than reading the whole file at once.

Remix also allows for composing multiple upload handlers with unstable_composeUploadHandlers, giving you the flexibility to, for instance, save certain files to disk while keeping others in memory.


Extra Reading & References 📚

Challenge

You are building a user profile feature and need to create a server-side endpoint to handle avatar uploads.

Your task is to implement the action function for a Remix Resource Route. This route will process a multipart/form-data request containing the user's avatar image and their user ID.

Requirements:

  1. The resource route is expected to handle a POST request.
  2. The incoming form data will contain two fields:
    • userId: A string (e.g., "user-123").
    • avatar: The uploaded file object.
  3. Use the unstable_parseMultipartFormData function to handle the upload stream.
  4. A pre-configured unstable_createFileUploadHandler is provided for you. It directs uploads to the "public/uploads" directory.
  5. After the form data is parsed, retrieve the userId string and the avatar file object.
  6. Return a JSON response with the following structure, using the data you extracted from the form:
    json
    {
      "success": true,
      "userId": "user-123",
      "fileName": "profile.png"
    }
    (Where "user-123" and "profile.png" are replaced with the actual values from the form data).

Expected result

Your completed code should implement the logic inside the action function.

The final implementation must:

  1. Asynchronously call unstable_parseMultipartFormData, passing it the request and the provided uploadHandler.
  2. Correctly await the result to get the formData object.
  3. Retrieve the userId value from formData. It should be a string.
  4. Retrieve the avatar value from formData. This will be a File object.
  5. If userId is not a string or avatar is not a File object, return a JSON error response with a 400 status code.
  6. If validation passes, return a successful json response containing { success: true, userId: userIdValue, fileName: avatarFile.name }.

An example of a correct successful return statement:
return json({ success: true, userId: "user-abc", fileName: "photo.jpg" });

typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.