npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

remix-strong-routes

v3.2.0

Published

Worry-free Remix routes with Typescript

Downloads

13

Readme

Remix Strong Routes

Worry-free Remix routes with Typescript 💪

Table of Contents

Background

Remix loaders and actions have generally good typescript support, but this project aims to ensure the data types passed around Remix routes are strongly typed. There are three things that can happen in a Remix loader or action:

  • Success
  • Failure
  • Redirects

This library exposes a tiny buildStrongRoute function that adds a small amount of validation logic to Remix's default routing behavior. The good part about this library, is that you do not have to use buildStrongRoute everywhere - you can opt in or out of its behavior per route.

Install

npm install remix-strong-routes

Usage

Returning Data inside loader and action

There are 3 possible options when returning data in a StrongLoader or StrongAction

  • Send data to your component with the succeed helper
  • Send data to your error boundary with the fail helper.
  • Perform an HTTP redirect using the redirect helper

Uncaught Errors

If your strong route loader or action calls toErrorBoundary, but was not built with a StrongErrorBoundary, the error will bubble up to the Remix root error boundary.

Define Types

import {
  StrongResponse,
  StrongRedirect,
  HttpStatusCode,
} from "remix-strong-routes";

type FooResponse = StrongResponse<"Foo", HttpStatusCode.OK>;

type BarResponse = StrongResponse<"Bar", HttpStatusCode.INTERNAL_SERVER_ERROR>;

type RedirectToLogin = StrongRedirect<
  "/login",
  HttpStatusCode.MOVED_PERMANENTLY
>;

Define Loader

import { strongLoader } from "remix-strong-routes";

const loader = strongLoader<BarResponse, FooResponse, RedirectToLogin>(
  async ({ context, request, params }, { fail, redirect, succeed }) => {
    // Try to validate a session
    if (await isUserLoggedIn(request)) {
      // Build a redirect object
      const redirectToLogin: RedirectToLogin = {
        data: "/login",
        status: HttpStatusCode.MOVED_PERMANENTLY,
      };

      // Return a type-safe redirect
      return redirect(redirectToLogin);
    }

    try {
      // Try to load some data
      const fooData = await getFooData();

      // Build a type-safe response object
      const fooResponse: FooResponse = {
        data: fooData,
        status: HttpStatusCode.OK,
      };

      // Return a type-safe success to your component
      return succeed(fooResponse);
    } catch (e) {
      // Build a type-safe response object
      const barResponse: BarResponse = {
        data: "Bar",
        status: HttpStatusCode.INTERNAL_SERVER_ERROR,
      };

      // Return a type-safe error to your error boundary
      return fail(barResponse);
    }
  },
);

Define Action

import { strongAction } from "remix-strong-routes";

const action - strongAction<
  BarResponse,
  FooResponse,
  RedirectToLogin
>(async (
  { context, request, params },
  { fail, redirect, succeed }
) => {
  // ... Same as the loader
});

Define Route Component

import { StrongComponent } from "remix-strong-routes";

const strongComponent: StrongComponent<FooResponse> = ({ status, data }) => {
  return (
    <ul>
      <li>Status: {status}</li>
      <li>Data: {data}</li>
    </ul>
  );
};

Define Error Boundary

import { StrongErrorBoundary } from "remix-strong-routes";

const strongErrorBoundary: StrongErrorBoundary<BarResponse> = ({
  status,
  data,
}) => {
  return (
    <ul>
      <li>Status: {status}</li>
      <li>Data: {data}</li>
    </ul>
  );
};

Configure & Export Route

import { buildStrongRoute } from "remix-strong-routes";

// Build strongly typed route exports
const route = buildStrongRoute<LoaderResponse>({
  routeId: "root",
  loader: strongLoader,
  action: strongAction,
  Component: strongComponent,
  ErrorBoundary: strongErrorBoundary,
});

// Export parts
export const action = route.action;
export const loader = route.loader;
export const ErrorBoundary = route.ErrorBoundary;
export default route.Component;

Call Another Route's Loader

This library uses buildStrongRoute to expose a more ergonomic useRouteLoaderData hook, which is a wrapper around the default Remix useRouteLoaderData hook. There are no guardrails in place within remix-strong-routes to enforce a route's parent-child relationship so it may be a defect if your application is not setup correctly. This may be improved when Remix exposes its route configurations under the hood.

The purpose of this hook is to prevent the need to remember a route's ID more than one time.

You can run npx remix routes --json to reveal all of the route IDs in your app.

import { buildStrongRoute } from "remix-strong-routes";

// Build strongly typed route exports
const route1 = buildStrongRoute<LoaderResponse>({
  // This routeId MUST be precisely what Remix expects
  routeId: "root",
  loader: strongLoader,
  action: strongAction,
  Component: strongComponent,
  ErrorBoundary: strongErrorBoundary,
});

const route2 = buildStrongRoute<LoaderResponse>({
  routeId: "routes/home",
  Component: () => {
    // If route1.routeId is not accurate, this will fail.
    const route1Data = route1.useRouteLoaderData();

    return <pre>{JSON.stringify(route1Data, null, 2)}</pre>;
  },
});

Contributing

PRs accepted.

License

MIT