clear-react-router 2.6.1 → 2.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,6 +25,17 @@ It provides first-class support for:
25
25
  > [Clear Safe Router](https://github.com/AndrewBubnov/clear-safe-router) ([npm](https://www.npmjs.com/package/clear-safe-router)) —
26
26
  > built on this runtime.
27
27
 
28
+ ## For AI agents
29
+
30
+ This library ships an agent skill: [`src/clear-router/skills/getting-started/SKILL.md`](src/clear-router/skills/getting-started/SKILL.md) —
31
+ setup, route semantics, caching, search params, navigation blocking, with three reference files.
32
+ Point your coding agent at it before writing code against this library:
33
+
34
+ ```bash
35
+ npx clear-react-router skill # print SKILL.md
36
+ npx clear-react-router skill install # copy it to .claude/skills/clear-react-router/ (--to <dir> for other agents)
37
+ ```
38
+
28
39
  ## Features
29
40
 
30
41
  - **Nested Routes** - Organize your UI with nested layouts and routes
@@ -88,6 +99,7 @@ The host rewrite only serves the app shell. To render your own UI for unknown cl
88
99
  | `defaultScrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | `auto` | Default scroll restoration behavior |
89
100
  | `revalidateOnFocus` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser tab regains focus |
90
101
  | `revalidateOnReconnect` | `boolean \| undefined` | `undefined` | Revalidate the current route's `loader` data when the browser regains an internet connection |
102
+ | `onBackgroundError` | `(error: Error, context: { path: string; route: RouteItem }) => void` | `undefined` | Fires when a background revalidation of the displayed route fails (after `invalidate()`, on tab focus/reconnect, or a failed polling tick). Displayed data is kept and `loaderError` is set next to it — use this for toasts, analytics or error reporting. Failures with nothing displayed (initial load) render `errorElement` as usual |
91
103
  | `enableCacheSnapshot` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
92
104
 
93
105
  > **Note:** Global lifecycle hooks wrap every route navigation. The global `defaultBeforeLoad` runs **before** the route-specific beforeLoad, while the global `defaultAfterLoad` runs **after** the route-specific afterLoad.
@@ -121,7 +133,7 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
121
133
  | `staleTime` | `number \| undefined` | Time in milliseconds before cached loader data is considered stale. Overrides Router.defaultStaleTime. If neither value is provided, data is stale immediately and navigation revalidates it. Use `Infinity` to never consider it stale |
122
134
  | `externalCache` | `boolean \| undefined` | The route's data freshness is owned by the loader's source (e.g. an external cache like TanStack Query): the router cache stores values but never claims freshness, so every navigation re-runs the loader. Inherited by children; a child can opt out with `false` |
123
135
  | `gcTime` | `number \| undefined` | How long, in milliseconds, an unused cache entry is kept in memory after you navigate away, before it's garbage-collected |
124
- | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Record<string, unknown>) => unknown \| Promise<unknown>>` | Defines route actions for data mutations. |
136
+ | `actions` | `({ params, context, searchParams, setContext, location }) => Record<string, (data: Payload) => unknown \| Promise<unknown>>` — any payload type; checked at `useSubmitAction<Payload>()` | Defines route actions for data mutations. |
125
137
  | `pollingInterval` | `number \| undefined` | Polling interval (in milliseconds) for automatically revalidating data while the route is active. Each tick refetches unconditionally, ignoring `staleTime` |
126
138
  | `scrollRestoration` | `boolean \| string[] \| undefined` | Restore scroll position when navigating back to this route. `true` restores the window scroll; a string array restores scroll inside specific scrollable elements, matched by their `id` |
127
139
  | `scrollRestorationBehavior` | `'auto' \| 'smooth' \| 'instant'` | Scroll restoration behavior |
@@ -133,11 +145,14 @@ Normalizes route configuration. Extracts dynamic params, builds nested paths.
133
145
  params: Record<string, string>; // Route parameters
134
146
  context: Record<string, unknown>; // Router context
135
147
  setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
136
- searchParams: Record<string, string>; // URL search parameters
148
+ searchParams: Record<string, string>; // URL search parameters — repeated keys collapse to the last value
149
+ urlSearchParams: URLSearchParams; // Standard accessor for repeated keys: urlSearchParams.getAll('tag')
137
150
  location: Location; // Route location
138
151
  }
139
152
  ```
140
153
 
154
+ Multi-value search params (`?tag=a&tag=b`) need the standard accessor: `searchParams.tag` returns only the last value, `urlSearchParams.getAll('tag')` returns both.
155
+
141
156
  see [`Location`](#uselocation) and [`Where you came from`](#where-you-came-from) for type details
142
157
 
143
158
  `beforeLoad` additionally receives:
@@ -645,11 +660,13 @@ Actions are available through the `useSubmitAction` and `useAction` hooks. After
645
660
 
646
661
  ```tsx
647
662
  actions?: ({ params, context, searchParams, setContext, location }) => ({
648
- save: async (data: Record<string, unknown>) => await api.updatePost(params.id, data),
649
- remove: async () => await api.deletePost(params.id),
663
+ save: async (data: PostInput) => await api.updatePost(params.id, data), // any payload type — checked at useSubmitAction<PostInput>()
664
+ remove: async () => await api.deletePost(params.id), // no-payload actions work as-is
650
665
  })
651
666
  ```
652
667
 
668
+ Declare the payload type at the hook — see [Typed payloads](#typed-payloads) under `useSubmitAction`.
669
+
653
670
  #### Arguments
654
671
 
655
672
  ```ts
@@ -657,7 +674,8 @@ actions?: ({ params, context, searchParams, setContext, location }) => ({
657
674
  params: Record<string, string>; // Route parameters
658
675
  context: Record<string, unknown>; // Router context
659
676
  setContext: Dispatch<SetStateAction<Record<string, unknown>>>; // Updates the router context
660
- searchParams: Record<string, string>; // URL search parameters
677
+ searchParams: Record<string, string>; // URL search parameters — repeated keys collapse to the last value
678
+ urlSearchParams: URLSearchParams; // Standard accessor for repeated keys: urlSearchParams.getAll('tag')
661
679
  location: Location; // Route location
662
680
  }
663
681
  ```
@@ -686,7 +704,29 @@ const CreateUserForm = () => {
686
704
  };
687
705
  ```
688
706
 
689
- `submit(data: Record<string, unknown>)` accepts a plain JS object, so it works with any form library that gives you validated values — not just native `<form>` submissions:
707
+ `submit(data)` accepts a plain JS object, so it works with any form library that gives you validated values — not just native `<form>` submissions.
708
+
709
+ ### Typed payloads
710
+
711
+ Declare the payload type once at the hook and every call is checked against it; the route `action` then receives it fully typed — no `Record<string, unknown>` casts:
712
+
713
+ ```tsx
714
+ const routes = createRouter([
715
+ {
716
+ path: '/settings',
717
+ element: <SettingsPage />,
718
+ actions: () => ({
719
+ save: async (data: SettingsInput) => saveSettings(data), // fully typed, no casts
720
+ }),
721
+ },
722
+ ]);
723
+
724
+ const { submit } = useSubmitAction<SettingsInput>('save');
725
+ submit({ delayMs: 300 }); // checked
726
+ submit({ delayMs: 'oops' }); // compile error
727
+ ```
728
+
729
+ The type argument is manual — actions are selected by a string at runtime, so the compiler cannot infer it from the route config (typed route trees are a larger project). Handlers without a custom type (`async () => 'ok'`, legacy `Record<string, unknown>` handlers) keep working unchanged.
690
730
 
691
731
  ```tsx
692
732
  import { useForm } from 'react-hook-form';
@@ -712,7 +752,7 @@ Return value:
712
752
 
713
753
  | Field | Type | Description |
714
754
  | -------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------- |
715
- | `submit` | `(data: Record<string, unknown>) => Promise<{ data: unknown; error: Error \| null }>` | Runs the action directly, from any form data source |
755
+ | `submit` | `(data: Payload) => Promise<{ data: unknown; error: Error \| null }>` — `Payload` from the type argument, `Record<string, unknown>` by default | Runs the action directly, from any form data source |
716
756
  | `onSubmit` | `(evt: SubmitEvent<HTMLFormElement>) => Promise<void>` | Ready-made handler for a native `<form onSubmit={...}>` |
717
757
  | `data` | `unknown` | Result of the last successful submission |
718
758
  | `error` | `Error \| null` | Error from the last failed submission |
@@ -774,15 +814,19 @@ type NavigationLocation = {
774
814
  pathname: string;
775
815
  search?: string | Record<string, string | number | boolean | null | undefined>;
776
816
  state?: unknown;
817
+ replace?: boolean; // rewrite the current history entry instead of pushing a new one
777
818
  };
778
819
 
779
820
  const navigate = useNavigate();
780
821
 
781
822
  navigate('/about'); // string
782
823
  navigate({ pathname: '/user/123', search: { user: 'Jane Doe' }, state: { from: 'home' } }); // NavigationLocation
824
+ navigate({ pathname: '/dashboard', replace: true }); // e.g. after login, so /login stays out of history
783
825
  navigate(-1); // go back
784
826
  ```
785
827
 
828
+ Redirects declared in `beforeLoad` (`redirect(...)`) always rewrite the current history entry — the user never saw the intermediate URL, so the Back button must not return into the redirect loop.
829
+
786
830
  **Note:** Navigation state can be accessed via [`useLocation()`](#uselocation):
787
831
 
788
832
  ```tsx
@@ -933,6 +977,8 @@ beforeLoad: async ({ location, redirect }) => {
933
977
 
934
978
  Returns the cached data loaded by the current route's `loader`, along with any errors from `loader` or `beforeLoad`. Data is cached, but whether a revisit reuses it depends on `staleTime`: by default cached data is stale immediately and the loader runs again.
935
979
 
980
+ > If a **background** revalidation of the displayed route fails (see [`onBackgroundError`](#router)), `data` stays on screen and `loaderError` is set next to it — render a small "stale data" banner from the same component. The page is only replaced by `errorElement` when there is nothing to display (e.g. the initial load fails).
981
+
936
982
  **Returns:**
937
983
 
938
984
  | Property | Type | Description |
@@ -1,3 +1,3 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { RouterProps } from '../types';
3
- export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, defaultExternalCache, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, enableCacheSnapshot, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
3
+ export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, defaultExternalCache, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, onBackgroundError, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, enableCacheSnapshot, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
@@ -6,6 +6,7 @@ declare class RouterConfig {
6
6
  isAnimated: RouterProps['isAnimated'];
7
7
  revalidateOnFocus: boolean;
8
8
  revalidateOnReconnect: boolean;
9
+ onBackgroundError?: RouterProps['onBackgroundError'];
9
10
  defaultHoverPrefetchDelay: number;
10
11
  defaultBeforeLoad?: ClientRouteItem['beforeLoad'];
11
12
  defaultAfterLoad?: ClientRouteItem['afterLoad'];
@@ -1,4 +1,4 @@
1
- export declare const useAction: (action: string, options?: import("../types").Options) => (arg: Record<string, unknown>) => Promise<{
1
+ export declare const useAction: <Payload = Record<string, unknown>>(action: string, options?: import("../types").Options) => (arg: Payload) => Promise<{
2
2
  data: unknown;
3
3
  error: Error | null;
4
4
  }>;
@@ -4,8 +4,8 @@ type Options = {
4
4
  onError?(arg: unknown): void;
5
5
  autoReset?: boolean;
6
6
  };
7
- export declare const useSubmitAction: (action: string, options?: Options) => {
8
- submit: (data: Record<string, unknown>) => Promise<{
7
+ export declare const useSubmitAction: <Payload = Record<string, unknown>>(action: string, options?: Options) => {
8
+ submit: (data: Payload) => Promise<{
9
9
  data: unknown;
10
10
  error: Error | null;
11
11
  }>;
package/dist/index.js CHANGED
@@ -27,20 +27,6 @@ var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
27
27
  return [synchronizer(subscribe, getState), setState];
28
28
  };
29
29
  //#endregion
30
- //#region utils/commitState.ts
31
- var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
32
- const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
33
- routeDataState.setState({
34
- routeItem,
35
- location,
36
- status: isError ? "error" : "active",
37
- loaderState: loaderStateValue
38
- });
39
- if (blockerState.getState() === "blocked") blockerState.setState("unblocked");
40
- if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
41
- history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
42
- };
43
- //#endregion
44
30
  //#region constants.ts
45
31
  var EMPTY_LOADER_STATE = {};
46
32
  var WINDOW_TOP = "__window_top__";
@@ -93,6 +79,7 @@ var RouterConfig = class {
93
79
  _defineProperty(this, "isAnimated", false);
94
80
  _defineProperty(this, "revalidateOnFocus", false);
95
81
  _defineProperty(this, "revalidateOnReconnect", false);
82
+ _defineProperty(this, "onBackgroundError", void 0);
96
83
  _defineProperty(this, "defaultHoverPrefetchDelay", 150);
97
84
  _defineProperty(this, "defaultBeforeLoad", void 0);
98
85
  _defineProperty(this, "defaultAfterLoad", void 0);
@@ -109,6 +96,37 @@ var RouterConfig = class {
109
96
  };
110
97
  var routerConfig = new RouterConfig();
111
98
  //#endregion
99
+ //#region runtime/backgroundError.ts
100
+ var handleBackgroundFailure = (loaderMap, path, error, routeItem, displayedData, syncCacheSnapshot) => {
101
+ const cachedState = loaderMap.get(path)?.state;
102
+ const entry = loaderMap.get(path);
103
+ const keptData = displayedData ?? cachedState?.data;
104
+ if (entry) {
105
+ entry.staleTime = 0;
106
+ syncCacheSnapshot();
107
+ }
108
+ routerConfig.onBackgroundError?.(error, {
109
+ path,
110
+ route: routeItem
111
+ });
112
+ return keptData ?? void 0;
113
+ };
114
+ //#endregion
115
+ //#region utils/commitState.ts
116
+ var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, loaderStateValue, location, replace }) => {
117
+ const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
118
+ routeDataState.setState({
119
+ routeItem,
120
+ location,
121
+ status: isError ? "error" : "active",
122
+ loaderState: loaderStateValue
123
+ });
124
+ if (blockerState.getState() === "blocked") blockerState.setState("unblocked");
125
+ if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
126
+ if (replace) history.replaceState(location.state ?? null, "", `${location.pathname}${location.search}`);
127
+ else history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
128
+ };
129
+ //#endregion
112
130
  //#region utils/commitNavigation.ts
113
131
  var commitNavigation = (callback, isCommited) => {
114
132
  if (!routerConfig.isAnimated || isCommited) return callback();
@@ -186,11 +204,16 @@ var isMobile = () => {
186
204
  };
187
205
  var sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
188
206
  var getPartialLoaderArgs = (contextState, location, routeItem) => {
207
+ const params = getParams(location, routeItem);
208
+ const context = contextState.getState();
209
+ const setContext = contextState.setState;
210
+ const urlSearchParams = new URLSearchParams(location.search);
189
211
  return {
190
- params: getParams(location, routeItem),
191
- context: contextState.getState(),
192
- setContext: contextState.setState,
193
- searchParams: Object.fromEntries(new URLSearchParams(location.search).entries()),
212
+ params,
213
+ context,
214
+ setContext,
215
+ searchParams: Object.fromEntries(urlSearchParams.entries()),
216
+ urlSearchParams,
194
217
  location
195
218
  };
196
219
  };
@@ -281,12 +304,14 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
281
304
  return await navigate({
282
305
  pathname,
283
306
  search,
284
- prevLocation
307
+ prevLocation,
308
+ replace: true
285
309
  });
286
310
  }
287
311
  return await navigate({
288
312
  ...redirected,
289
- prevLocation
313
+ prevLocation,
314
+ replace: true
290
315
  });
291
316
  };
292
317
  try {
@@ -371,12 +396,25 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
371
396
  });
372
397
  if (!result || signal.aborted) return;
373
398
  const { location: currentLocation } = routeDataState.getState();
374
- if (toCacheKey(`${currentLocation.pathname}${currentLocation.search ?? ""}`) !== getPath(nextLocation)) return;
399
+ const currentPath = toCacheKey(`${currentLocation.pathname}${currentLocation.search ?? ""}`);
400
+ if (currentPath !== getPath(nextLocation)) return;
401
+ if (result.error) {
402
+ const keptData = handleBackgroundFailure(routerState.loaderMap, currentPath, result.error, routeItem, routeDataState.getState().loaderState.data, syncCacheSnapshot);
403
+ routeDataState.setState((prevState) => ({
404
+ ...prevState,
405
+ loaderState: {
406
+ data: keptData ?? null,
407
+ loaderError: result.error,
408
+ beforeLoadError: null
409
+ }
410
+ }));
411
+ return;
412
+ }
375
413
  routeDataState.setState((prevState) => ({
376
414
  ...prevState,
377
415
  loaderState: {
378
416
  data: result.data,
379
- loaderError: result.error,
417
+ loaderError: null,
380
418
  beforeLoadError: null
381
419
  }
382
420
  }));
@@ -441,8 +479,9 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
441
479
  });
442
480
  };
443
481
  const navigate = async (rawLocation) => {
482
+ const { replace: replaceEntry, ...locationFields } = rawLocation;
444
483
  const nextLocation = {
445
- ...rawLocation,
484
+ ...locationFields,
446
485
  search: rawLocation.search ?? ""
447
486
  };
448
487
  if (checkBlocked(nextLocation)) return;
@@ -467,7 +506,8 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
467
506
  commitNavigation(() => commitState({
468
507
  location: nextLocation,
469
508
  routeItem: nextItem,
470
- loaderStateValue
509
+ loaderStateValue,
510
+ replace: replaceEntry === true
471
511
  }));
472
512
  clearCurrentGcTimeout(nextItem, nextLocation);
473
513
  afterLoad(nextItem, nextLocation, params);
@@ -496,24 +536,41 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
496
536
  force: !options?.staleOnly
497
537
  });
498
538
  const activeLocation = routeDataState.getState().location;
499
- if (result && normalizePath(pathname) === normalizePath(`${activeLocation.pathname}${activeLocation.search}`)) routeDataState.setState((prevState) => ({
539
+ if (result && normalizePath(pathname) === normalizePath(`${activeLocation.pathname}${activeLocation.search}`)) if (result.error) {
540
+ const keptData = handleBackgroundFailure(loaderMap, pathname, result.error, routeItem, routeDataState.getState().loaderState.data, syncCacheSnapshot);
541
+ routeDataState.setState((prevState) => ({
542
+ ...prevState,
543
+ loaderState: {
544
+ data: keptData ?? null,
545
+ loaderError: result.error,
546
+ beforeLoadError: null
547
+ },
548
+ status: keptData != null ? "active" : "error"
549
+ }));
550
+ } else routeDataState.setState((prevState) => ({
500
551
  ...prevState,
501
552
  loaderState: {
502
553
  data: result.data,
503
- loaderError: result.error,
554
+ loaderError: null,
504
555
  beforeLoadError: null
505
556
  },
506
- status: result.error ? "error" : "active"
557
+ status: "active"
507
558
  }));
508
559
  return {
509
560
  path: pathname,
561
+ matched: true,
510
562
  ...result
511
563
  };
512
564
  };
513
565
  const invalidateItem = async (rawPathname, options) => {
514
566
  const pathname = toCacheKey(rawPathname);
515
567
  const routeItem = findRoute(separatePathname(pathname));
516
- if (!routeItem) return [];
568
+ if (!routeItem) return [{
569
+ path: rawPathname,
570
+ matched: false,
571
+ data: null,
572
+ error: null
573
+ }];
517
574
  const targetPathname = separatePathname(pathname);
518
575
  const isPattern = targetPathname.split("/").filter(Boolean).some(isParamSegment);
519
576
  const pathnameSet = /* @__PURE__ */ new Set();
@@ -789,17 +846,7 @@ var createRouterInstance = (synchronizer) => {
789
846
  const { routeItem, location } = routerState.routeDataState.getState();
790
847
  if (!routeItem) throw new Error("Route not found");
791
848
  if (!routeItem.actions) throw new Error("Route action creator not found");
792
- const context = routerState.contextState.getState();
793
- const setContext = routerState.contextState.setState;
794
- const params = getParams(location, routeItem);
795
- const searchParams = Object.fromEntries(new URLSearchParams(location.search).entries());
796
- const action = routeItem.actions({
797
- context,
798
- setContext,
799
- params,
800
- location,
801
- searchParams
802
- })[actionKey];
849
+ const action = routeItem.actions(getPartialLoaderArgs(routerState.contextState, location, routeItem))[actionKey];
803
850
  if (!action) throw new Error(`Action "${actionKey}" not found`);
804
851
  return action;
805
852
  };
@@ -1032,7 +1079,7 @@ var renderElement = (Component) => {
1032
1079
  var EmptyBoundary = ({ children }) => children;
1033
1080
  var MOBILE_CACHE_SIZE = 60;
1034
1081
  var DESKTOP_CACHE_SIZE = 150;
1035
- var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, defaultExternalCache, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
1082
+ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, defaultExternalCache, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, onBackgroundError, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
1036
1083
  const isMobileDevice = isMobile();
1037
1084
  const resolvedMaxCacheSize = maxCacheSize ?? (isMobileDevice ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE);
1038
1085
  const resolvedDefaultPrefetch = defaultPrefetch ?? (isMobileDevice ? "viewport" : "hover");
@@ -1057,6 +1104,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
1057
1104
  maxCacheSize: resolvedMaxCacheSize,
1058
1105
  revalidateOnFocus,
1059
1106
  revalidateOnReconnect,
1107
+ onBackgroundError,
1060
1108
  defaultScrollRestorationBehavior,
1061
1109
  enableCacheSnapshot
1062
1110
  });
@@ -0,0 +1,4 @@
1
+ import { type RouteItem, type RouterState } from '../types';
2
+ type LoaderMap = RouterState['loaderMap'];
3
+ export declare const handleBackgroundFailure: (loaderMap: LoaderMap, path: string, error: Error, routeItem: RouteItem | undefined, displayedData: unknown, syncCacheSnapshot: () => void) => unknown;
4
+ export {};
@@ -1,2 +1,3 @@
1
1
  import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
2
+ export declare const resetMissedInvalidationWarnings: () => void;
2
3
  export declare const createInvalidate: ({ routeDataState, loaderMap, loadingPromises }: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
@@ -1,2 +1,4 @@
1
1
  import { Location, RevalidateCache, RouterState } from '../types';
2
- export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (rawLocation: Location) => Promise<void>;
2
+ export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (rawLocation: Location & {
3
+ replace?: boolean;
4
+ }) => Promise<void>;
package/dist/types.d.ts CHANGED
@@ -12,7 +12,10 @@ type LoaderArgs = {
12
12
  context: Record<string, unknown>;
13
13
  params: Record<string, string>;
14
14
  setContext: SetStateFn<Record<string, unknown>>;
15
+ /** Single-value convenience view; repeated keys collapse to the last value. */
15
16
  searchParams: Record<string, string>;
17
+ /** Standard accessor for repeated keys: `urlSearchParams.getAll('tag')`. */
18
+ urlSearchParams: URLSearchParams;
16
19
  location: Location;
17
20
  };
18
21
  export type BeforeLoad = (arg: LoaderArgs & {
@@ -56,8 +59,9 @@ export type ClientRouteItem = {
56
59
  params: Record<string, string>;
57
60
  searchParams: Record<string, string>;
58
61
  }) => Promise<void> | void;
59
- actions?: (arg: LoaderArgs) => Record<string, (arg: Record<string, unknown>) => Promise<unknown> | Promise<void> | void | unknown>;
62
+ actions?: (arg: LoaderArgs) => Record<string, ActionHandler>;
60
63
  };
64
+ export type ActionHandler = (arg: never) => Promise<unknown> | Promise<void> | void | unknown;
61
65
  export type RouteItem = ClientRouteItem & {
62
66
  element: RenderElement;
63
67
  pattern: string;
@@ -122,6 +126,15 @@ export type RouterProps = {
122
126
  revalidateOnFocus?: boolean;
123
127
  revalidateOnReconnect?: boolean;
124
128
  context?: Record<string, unknown>;
129
+ /**
130
+ * Fires when a background revalidation of a page-serving route fails (invalidate,
131
+ * focus/reconnect, polling). Displayed data is kept; use this for toasts, analytics
132
+ * or error reporting. The initial load keeps its errorElement path.
133
+ */
134
+ onBackgroundError?: (error: Error, context: {
135
+ path: string;
136
+ route: RouteItem;
137
+ }) => void;
125
138
  /** Enables cache snapshot tracking for devtools. `useCacheSnapshot` returns an empty list without it. */
126
139
  enableCacheSnapshot?: boolean;
127
140
  };
@@ -166,7 +179,9 @@ export type RouterState = {
166
179
  };
167
180
  export type RouterType = {
168
181
  runtime: {
169
- navigate(arg: Location): Promise<void>;
182
+ navigate(arg: Location & {
183
+ replace?: boolean;
184
+ }): Promise<void>;
170
185
  invalidate(pathList?: string | string[], options?: InvalidateOptions): Promise<InvalidateResult[]>;
171
186
  prefetch(location: Location, signal?: AbortSignal): Promise<void>;
172
187
  syncCacheSnapshot(): void;
@@ -181,7 +196,7 @@ export type RouterType = {
181
196
  (arg: NavigationLocation | string | -1): Promise<void>;
182
197
  <const TPath extends string>(arg: NavigatePathArg<TPath>): Promise<void>;
183
198
  };
184
- useAction(action: string, options?: Options): (arg: Record<string, unknown>) => Promise<{
199
+ useAction<Payload = Record<string, unknown>>(action: string, options?: Options): (arg: Payload) => Promise<{
185
200
  data: unknown;
186
201
  error: Error | null;
187
202
  }>;
@@ -204,10 +219,13 @@ export type InvalidateResult = {
204
219
  path: string;
205
220
  data: unknown;
206
221
  error: Error | null;
222
+ matched?: boolean;
207
223
  };
208
224
  export type SearchObject = Record<string, string | number | boolean | null | undefined>;
209
225
  export type NavigationLocation = Omit<Location, 'search'> & {
210
226
  search?: string | SearchObject;
227
+ /** Rewrite the current history entry instead of pushing a new one. */
228
+ replace?: boolean;
211
229
  };
212
230
  export type PathParams = Record<string, string | number>;
213
231
  export type ParamsFor<TPath extends string> = TPath extends `${string}:${infer Param}/${infer Rest}` ? {
@@ -261,6 +279,8 @@ export type NavigatePathInput = {
261
279
  params?: PathParams;
262
280
  search?: string | SearchObject;
263
281
  state?: unknown;
282
+ /** Rewrite the current history entry instead of pushing a new one. */
283
+ replace?: boolean;
264
284
  };
265
285
  export type Synchronizer = <T>(subscribe: (updater: () => void) => () => void, getSnapshot: () => T, getServerSnapshot?: () => T) => T;
266
286
  export {};
@@ -3,6 +3,7 @@ type CommitState = {
3
3
  location: Location;
4
4
  loaderStateValue: LoaderState;
5
5
  routeItem?: RouteItem;
6
+ replace?: boolean;
6
7
  };
7
- export declare const createCommitState: ({ routeDataState, blockerState }: RouterState) => ({ routeItem, loaderStateValue, location }: CommitState) => void;
8
+ export declare const createCommitState: ({ routeDataState, blockerState }: RouterState) => ({ routeItem, loaderStateValue, location, replace }: CommitState) => void;
8
9
  export {};
@@ -20,6 +20,7 @@ export declare const getPartialLoaderArgs: (contextState: RouterState["contextSt
20
20
  context: Record<string, unknown>;
21
21
  setContext: import("../types").SetStateFn<Record<string, unknown>>;
22
22
  searchParams: Record<string, string>;
23
+ urlSearchParams: URLSearchParams;
23
24
  location: Location;
24
25
  };
25
26
  export declare const isVerticalScroll: (el: Element | null) => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.6.1",
3
+ "version": "2.6.3",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {
@@ -60,7 +60,9 @@ navigate({ path: '/users/:userId', params: { userId: '42' } }); // typed templat
60
60
  The whole surface, one line each — details live in the references (load by task
61
61
  below):
62
62
 
63
- - **Routing** — object routes with nested `children` (relative paths), `layout` /
63
+ - **Routing** — `replace?: boolean` on any navigation rewrites the current history
64
+ entry (post-login flows); redirects declared in `beforeLoad` always rewrite the
65
+ current entry, so Back never returns into a redirect loop. Object routes with nested `children` (relative paths), `layout` /
64
66
  `layouts` nesting (outermost-first, inherited), lazy `element`s, catch-all `*`,
65
67
  typed path templates in `Link` (`path` + `params`) and `useNavigate`, active-link
66
68
  matching with `exact`, custom element rendering via `as`.
@@ -72,6 +74,10 @@ below):
72
74
  attempts get an `attempt` counter; aborted flights never commit.
73
75
  - **Polling** — `pollingInterval` re-runs the loader while the route is active; stops
74
76
  on leave, restarts on return.
77
+ - **Background errors** — a failed background revalidation (invalidate, focus/reconnect, polling)
78
+ keeps displayed data and reports instead of swapping the page: `loaderError` is set next to the
79
+ data, `onBackgroundError(error, { path, route })` fires on `<Router>`, the cache entry is demoted
80
+ to stale. The errorElement path is reserved for failures with nothing to display (initial load).
75
81
  - **Loading UX** — `optimistic` (instant cache hit for revisited keys),
76
82
  `keepPreviousData` (previous data held during pending, same element),
77
83
  `loaderFallback` / `defaultLoaderFallback`, `minLoaderDuration` /
@@ -102,10 +108,11 @@ below):
102
108
 
103
109
  - **No context, no provider.** Hooks read a global singleton; render `<Router>` once.
104
110
  - **The loader is the data owner.** `loader` receives
105
- `{ params, searchParams, context, setContext, location, signal, attempt }` and
111
+ `{ params, searchParams, urlSearchParams, context, setContext, location, signal, attempt }` and
106
112
  returns anything serializable. Its result is cached per **`pathname + search`** —
107
113
  a different query string is a different entry. `searchParams` is a plain object
108
- (multi-value keys collapse; read `location.search` raw for repeated keys).
114
+ (repeated keys collapse to the last value); use `urlSearchParams.getAll('tag')` for
115
+ multi-value keys.
109
116
  - **`beforeLoad` is for guards, not data.** Redirect via `redirect()` in its args; a
110
117
  thrown/rejected error lands in `beforeLoadError` and renders `errorElement`.
111
118
  - **Search params are navigations.** `setSearchParams` performs a full navigation: it
@@ -120,6 +127,19 @@ below):
120
127
  superseding a navigation cancels the previous flight. Do not create your own
121
128
  `AbortController` for loaders.
122
129
 
130
+ ## Scope boundaries
131
+
132
+ - Route URL state that must **survive a reload, be shareable by link, or drive the
133
+ back button**. Everything else — open tabs, wizard steps, open accordions — is
134
+ plain component state (`useState` + a tabs/stepper component). Do not route
135
+ transient UI state.
136
+ - "Shareable" counts only when a link without the state **loses its meaning**
137
+ (an onboarding step: yes; an open spoiler: no).
138
+ - Embedded panels that do need back or links (configurators, galleries) read and
139
+ write their slice of the host page's search params — they never get a second router.
140
+ - One `<Router>` per page. This is a client-side SPA router by design; there is
141
+ no SSR support.
142
+
123
143
  ## Load by task
124
144
 
125
145
  - Route config, nesting, layouts, params, catch-all, lazy components →
@@ -134,8 +154,12 @@ below):
134
154
 
135
155
  ## API discovery
136
156
 
137
- Inspect `src/clear-router/index.ts` (the only public entry point), then
138
- `src/clear-router/types.ts` for `RouteItem` and hook signatures. The playground
157
+ In an installed package, the public surface is
158
+ `node_modules/clear-react-router/dist/index.d.ts` — every exported symbol with its
159
+ signatures; consult `dist/index.js` only when runtime behavior is unclear.
160
+ In the repository, the entry point is `src/clear-router/index.ts` and
161
+ `src/clear-router/types.ts` holds `RouteItem` and hook signatures. The playground
139
162
  (`src/playground/routes.tsx`) shows every feature wired end-to-end against a fake
140
163
  in-browser server; the search page (`src/playground/SearchPage.tsx`) is the
141
- reference for URL-owned query state with TanStack Table.
164
+ reference for URL-owned query state with TanStack Table. Live demo:
165
+ https://clear-react-router.vercel.app/playground.