Package Exports
- cw-router
Readme
cw-router
A minimal, production-ready virtual router for Preact, designed specifically for embedded widgets that use a query parameter as a virtual URL.
Why cw-router?
Most routers (like React Router or Wouter) are designed for full-page applications where window.location.pathname is the source of truth. cw-router is different:
- Virtual URL: Uses the
_cwquery parameter (e.g.,?_cw=/status/123) instead of the pathname. - Embedded Friendly: Perfect for widgets embedded on third-party sites where you can't control the URL path.
- Ultra Lightweight: Under 2KB (approx. 1.96 KB minified).
- Preact Native: Built for Preact with zero external dependencies.
Installation
pnpm add cw-router
# or
npm install cw-routerCore Concept: The _cw Contract
Routing is driven exclusively by the _cw query parameter. The router automatically normalizes and matches these values:
_cw value |
Resolved Virtual Route |
|---|---|
| absent or empty | / (home) |
/status/123 |
/status/:id |
/status?c=123 |
/status/:id (legacy support) |
/password |
/password |
| unknown | User-defined fallback |
Usage Example
import { Route, Switch, Link, useLocation } from "cw-router";
const App = () => {
return (
<div>
<nav>
<Link href="/">Home</Link>
<Link href="/password">Change Password</Link>
</nav>
<Switch>
<Route path="/" component={Home} />
<Route path="/status/:id" component={Status} />
<Route path="/password" component={Password} />
{/* Fallback for unknown routes */}
<Route component={NotFound} />
</Switch>
</div>
);
};
const Status = ({ params }) => {
return <div>Order ID: {params.id}</div>;
};API Reference
useLocation()
A hook that returns the current virtual path and a navigation function.
const [location, navigate] = useLocation();
// Navigate to a new route
navigate("/status/456");
// Replace the current state
navigate("/home", { replace: true });<Route />
Renders content if the path matches.
path?: string: The pattern to match (e.g.,/user/:id).component?: Component: Component to render (receivesparamsprop).children?: Alternative way to render content.
<Switch />
Iterates through children and renders the first matching <Route />. Useful for "Not Found" logic.
<Link />
A wrapper for <a> that prevents full page reloads and updates the virtual location.
href: string: The target virtual path.replace?: boolean: UsereplaceStateinstead ofpushState.
Features
History Integration
cw-router patches window.history.pushState and window.history.replaceState to ensure that any programmatic navigation updates your components instantly, even if done outside of the React/Preact lifecycle.
Parameter Support
Supports dynamic segments like :id. These are passed as a params object to your route components.
License
ISC