https://github.com/dvtng/core-router
Primitives for building your own router
https://github.com/dvtng/core-router
Last synced: 28 days ago
JSON representation
Primitives for building your own router
- Host: GitHub
- URL: https://github.com/dvtng/core-router
- Owner: dvtng
- License: mit
- Created: 2020-01-18T00:28:03.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2026-03-03T16:44:03.000Z (3 months ago)
- Last Synced: 2026-03-03T20:48:50.785Z (3 months ago)
- Language: TypeScript
- Homepage:
- Size: 48.8 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# core-router
Primitives for building your own router.
## Matching URLs with `match()`
`match()` provides flexible rule-based URL matching.
You can:
1. Use a path-only rule:
```js
match({ path: "/account/:accountId" }, "/account/123");
result = {
params: {
accountId: "123";
}
}
```
2. Combine path, search params, and a condition:
```js
match(
{
path: "/account/:accountId",
search: {
from: ":fromDate?",
to: ":toDate?"
},
condition: ({ params }) => {
return isDate(params.fromDate) && isDate(params.toDate);
}
},
"/account/123?from=2020-01-01&to=2020-01-31"
);
result = {
params: {
accountId: "123",
fromDate: "2020-01-01",
toDate: "2020-01-31"
}
};
```
3. Or fallback to completely custom logic:
```js
match(
{
condition: ({ url }) => {
return url.hash === "#secret";
}
},
"/you/must/have/the#secret"
);
result = {
params: {}
};
```
Absolute URLs will only match if they belong to the same domain:
```js
// On https://foo.com:
match({ path: "/hello" }, "https://bar.com/hello");
result = null;
```
Params will be decoded for you:
```js
match({ search: { q: ":searchTerms" } }, "/?q=hello%20world");
result = {
params: {
searchTerms: "hello world"
}
};
```
## Generating URLs with `toHref()`
Any rule that can be used for `match()` can also be used to generate a relative URL.
```js
toHref({ path: "/account/:accountId" }, { accountId: "123" });
result = "/account/123";
```
If required params are not supplied, an error will be thrown:
```js
toHref({ path: "/account/:accountId" }, {});
// Error!
```
Similarly, if the `condition` is not met, an error will alos be thrown:
```js
toHref(
{
condition: ({ url }) => url.hash === "#secret"
},
"/#incorrect"
);
// Error!
```
This ensures that for any rule, a URL generated by `toHref()` will also `match()`:
```js
const href = toHref(myRule, myParams);
const matchResult = match(myRule, href);
expect(matchResult).not.toBe(null);
expect(matchResult.params).toEqual(myParams);
```