New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

esroute

Package Overview
Dependencies
Maintainers
1
Versions
24
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

esroute

A small efficient framework-agnostic client-side routing library, written in TypeScript.

  • 0.9.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

esroute

A small efficient framework-agnostic client-side routing library, written in TypeScript.

It is currently under development and API might slightly change.

Demo

Features

Those features may be the ones you are looking for.

🌈 Framework agnostic

Esroute is written with no external dependencies, so it does not require you to use a library.

🧭 Concise navigation API

Navigation with esroute is straight-forward. There is a go() method on the router instance. Examples:

// Navigate to some page
router.go("/some/path", { search: { foo: "bar" }, state: 42 });
// Update search params, keeping previous path and state. Will use history.replaceState() by default.
router.go((prev) => ({
  search: { foo: "baz" },
}));

🕹 Simple configuration

A configuration can look as simple as this:

import { createRouter } from "esroute";

const router = createRouter({
  routes: {
    "": ({ go }, next) => next ?? go("/foo"),
    foo: () => load("routes/foo.html"),
    nested: {
      "": load("routes/nested/index.html"),
      "*": ({ params: [param] }) => load("routes/nested/dynamic.html", param),
    },
  },
});

router.onResolve(({ value }) => render(value));
router.init();

You can compose the configuration as you like, which allows you to easily modularize you route configuration:

const router = createRouter({
  routes: {
    "": ({ go }) => go("/mod1"),
    mod1: mod1Routes,
    merged: {
      ...mod2Routes,
      ...mod3Routes,
    },
  },
});

✅ Typesafe value resolution

The router can be restricted to allow only certain resolution types.

const router = createRouter<string>({
  routes: {
    "": () => "some nice value",
    async: loadString(),
    weird: () => 42, // TS Error
  },
});

🏎 Fast startup and runtime

esroute comes with no dependencies and is quite small.

The route resolution is done by traversing the route spec that is used to configure the app routes (no preprocessing required). The algorithm is based on simple string comparisons (no regex matching).

🛡 Route guards

You can prevent resolving routes by redirecting to another route within a guard:

const router = createRouter({
  routes: {
    members: {
      "?": async ({ go }) => (await isLoggedIn()) || go("/login"),
      ...memberRoutes,
    },
  },
});

In the example above, a logged in user will see the profile and a logged-out user will see the login page instead.

Another example:

const router = createRouter({
  routes: {
    "*": {
      "?": async ({ go, params: [id] }) =>
        (await exists(id)) || go("/not-found"),
      ...someRoutes,
    },
  },
});

🦄 Virtual routes

When route resolution is done, all virtual routes ("") on the path to the leaf are collected and then rendered from leaf to root.

This allows creating various szenarios. Here are some examples:

Composed rendering
const router = createRouter({
  routes: {
    foo: {
      "": ({}, next) => (next ? `foo${next}` : "foo"),
      bar: () => `bar`,
    },
  },
});

In this case the route /foo will resolve to "foo" and the route /foo/bar will resolve to foobar. With this pattern you can implement index routes and frames.

Anonymous grouping of routes

In some cases you might want to attach rendering af a common frame or a guard to a set of routes without placing them on a separate named parent route. This is where virtual routes come into play:

const router = createRouter({
  routes: {
    "": {
      "": ({ go }, value) => (loggedIn ? value ?? renderIndex() : go("/login")),
      ...memberRoutes,
    },
    login: () => renderLogin(),
  },
});

In this sczenario we have the memberRoutes next to the /login route.

Router configuration

The createRouter factory takes a RouterConf object as parameter.

The Routes

Example:

const routes: Routes = {
  "": ({ go }, value) => (isLoggedIn || value) ?? go(["login"]),
  x: resolveX,
  nested: {
    "": resolveNestedIndex,
    y: resolveY,
    level2: {
      z: resolveZ,
    },
    "*": {
      foo: ({ params: [myParam] }) => resolveFoo(myParam),
    },
  },
};

The RouterConf

RouterConf provides some router-specific configuration:

interface RouterConf<T> {
  routes?: Routes<T>;
  notFound?: Resolve<T>;
  noClick?: boolean;
  onResolve?: (resolved: Resolved<T>) => void;
}

RouterConf.routes The routes configuration. You may modify this object to change the routes. Be sure to call router.init() after the current route is configured.

RouterConf.notFound A fallback resolve funuction to use, if a route could not be found. By default it redirects to the root path '/'.

RouterConf.noClick Whether the click handler for anchor elements shall not be installed. This might make sense, if you want to take more control over how anchor clicks are handled.

RouterConf.onResolve A callback that is invoked whenever a route is resolved.

Keywords

FAQs

Package last updated on 16 Apr 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc