0.1.5 • Published 5 months ago

ganu-router v0.1.5

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

Ganu Router

A lightweight TypeScript router for Single Page Applications with support for path parameters, route guards, and browser history management.

Installation

npm install ganu-router

Quick Start

import { createRouter } from "ganu-router";

const router = createRouter();

// Initialize with routes
router.initialize({
  routes: [
    {
      path: "/",
      handler: () => {
        document.getElementById("app").innerHTML = "Home";
      },
    },
    {
      path: "/users/:id",
      handler: ({ params }) => {
        document.getElementById("app").innerHTML = `User: ${params.id}`;
      },
      beforeLoad: ({ params }) => {
        // Guard route access
        if (!isAuthenticated()) {
          throw router.navigate("/login");
        }
      },
    },
  ],
});

router.navigate("/users/123");

API Reference

createRouter()

Creates a new router instance.

router.initialize(options?: RouterOptions)

Initializes the router with optional configuration:

type RouterOptions = {
  routes?: Array<RouteConfig>; // Initial routes
  window?: Window; // Custom window object for SSR
};

router.addRoute(route: RouteConfig)

Registers a single route dynamically. Typically, adding a route within the router.initialize method is sufficient for most use cases.

type RouteConfig = {
  path: string; // URL pattern
  handler: RouteHandler; // RouteConfig handler function
  beforeLoad?: BeforeLoadHandler; // Guard hook
};

router.addRoutes(routes: Array<RouteConfig>)

Registers multiple routes at once. Typically, adding routes within the router.initialize method is sufficient for most use cases.

router.navigate(path: string, options?: NavigateOptions)

Navigates to a new route:

type NavigateOptions = {
  replace?: boolean; // Replace current history entry
  state?: any; // State data for history entry
};

RouteConfig Patterns

  • Static paths: /about
  • Parameters: /users/:id
  • Wildcards: /docs/* or /blog/*/comments
  • Query strings: /docs?lang=en or /search?q=ganu&sort=asc

RouteConfig Guards

Use beforeLoad to protect routes or perform actions before navigation:

router.addRoute({
  path: "/admin",
  handler: showAdminPanel,
  beforeLoad: ({ path, params }) => {
    if (!hasAdminAccess()) {
      throw router.navigate("/login");
    }
  },
});

License

MIT

0.1.2

5 months ago

0.1.4

5 months ago

0.1.3

5 months ago

0.1.5

5 months ago

0.1.0

5 months ago

0.1.1

5 months ago

0.0.3

6 months ago

0.0.2

6 months ago

0.0.1

6 months ago