{"_id":"@brendonovich/solidjs__router","name":"@brendonovich/solidjs__router","dist-tags":{"latest":"0.15.0"},"versions":{"0.15.0":{"name":"@brendonovich/solidjs__router","description":"Universal router for SolidJS","author":{"name":"Ryan Carniato"},"contributors":[{"name":"Ryan Turnquist"}],"license":"MIT","version":"0.15.0","homepage":"https://github.com/solidjs/solid-router#readme","repository":{"type":"git","url":"git+https://github.com/solidjs/solid-router.git"},"publishConfig":{"access":"public"},"type":"module","main":"dist/index.js","types":"dist/index.d.ts","exports":{".":{"solid":"./dist/index.jsx","default":"./dist/index.js"}},"sideEffects":false,"devDependencies":{"@babel/core":"^7.23.9","@babel/preset-typescript":"^7.23.3","@changesets/cli":"^2.27.1","@rollup/plugin-babel":"6.0.4","@rollup/plugin-node-resolve":"15.2.3","@rollup/plugin-terser":"0.4.4","@types/jest":"^29.5.11","@types/node":"^20.11.14","babel-preset-solid":"^1.9.2","jsdom":"^24.0.0","prettier":"^2.7.0","rollup":"^4.9.6","solid-js":"^1.9.2","typescript":"^5.3.3","vite":"^5.4.8","vite-plugin-solid":"^2.9.1","vitest":"^2.1.2"},"peerDependencies":{"solid-js":"^1.8.6"},"scripts":{"build":"tsc && rollup -c","test":"vitest run && npm run test:types","test:watch":"vitest","test:types":"tsc --project tsconfig.test.json","pretty":"prettier --write \"{src,test}/**/*.{ts,tsx}\""},"bugs":{"url":"https://github.com/solidjs/solid-router/issues"},"_id":"@brendonovich/solidjs__router@0.15.0","_integrity":"sha512-TtLMwxuYE1tzupLYmKmDyQyyLj9hZeNa+jWMc2g6ItTMwJW1io8Y+lbPpCAv674mG2BF6v5U6GD61fpY7la4fg==","_resolved":"/private/var/folders/09/05vxh1_d3q3c07yj9c313c700000gn/T/d160d3206e51daf6d2f853268b232e36/brendonovich-solidjs__router-0.15.0.tgz","_from":"file:brendonovich-solidjs__router-0.15.0.tgz","_nodeVersion":"20.11.0","_npmVersion":"10.2.4","dist":{"integrity":"sha512-TtLMwxuYE1tzupLYmKmDyQyyLj9hZeNa+jWMc2g6ItTMwJW1io8Y+lbPpCAv674mG2BF6v5U6GD61fpY7la4fg==","shasum":"57241bf9b28c938e84386a5ac7fc5a24418cd8de","tarball":"https://registry.npmjs.org/@brendonovich/solidjs__router/-/solidjs__router-0.15.0.tgz","fileCount":42,"unpackedSize":179254,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIHiM/KOm/so2xiGvbAtv7RDEXvnBafZjfOahKKwb6PBAAiA9q1Q4xFEtq7NnEt3F5ZkbiLw4kMaYqE9guQKSH+2nxg=="}]},"_npmUser":{"name":"brendonovich","email":"brendonovich@outlook.com"},"directories":{},"maintainers":[{"name":"brendonovich","email":"brendonovich@outlook.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/solidjs__router_0.15.0_1730715557801_0.9106817185591649"},"_hasShrinkwrap":false}},"time":{"created":"2024-11-04T10:19:17.632Z","0.15.0":"2024-11-04T10:19:18.040Z","modified":"2024-11-04T10:19:18.388Z"},"maintainers":[{"name":"brendonovich","email":"brendonovich@outlook.com"}],"description":"Universal router for SolidJS","homepage":"https://github.com/solidjs/solid-router#readme","repository":{"type":"git","url":"git+https://github.com/solidjs/solid-router.git"},"contributors":[{"name":"Ryan Turnquist"}],"author":{"name":"Ryan Carniato"},"bugs":{"url":"https://github.com/solidjs/solid-router/issues"},"license":"MIT","readme":"<p>\n  <img src=\"https://assets.solidjs.com/banner?project=Router&type=core\" alt=\"Solid Router\" />\n</p>\n\n# Solid Router [![npm Version](https://img.shields.io/npm/v/@solidjs/router.svg?style=flat-square)](https://www.npmjs.org/package/@solidjs/router)\n\n**Version 0.10.0 requires Solid v1.8.4 or later.**\n\nA router lets you change your view based on the URL in the browser. This allows your \"single-page\" application to simulate a traditional multipage site. To use Solid Router, you specify components called Routes that depend on the value of the URL (the \"path\"), and the router handles the mechanism of swapping them in and out.\n\nSolid Router is a universal router for SolidJS - it works whether you're rendering on the client or on the server. It was inspired by and combines paradigms of React Router and the Ember Router. Routes can be defined directly in your app's template using JSX, but you can also pass your route configuration directly as an object. It also supports nested routing, so navigation can change a part of a component, rather than completely replacing it.\n\nIt supports all of Solid's SSR methods and has Solid's transitions baked in, so use it freely with suspense, resources, and lazy components. Solid Router also allows you to define a preload function that loads parallel to the routes ([render-as-you-fetch](https://epicreact.dev/render-as-you-fetch/)).\n\n- [Getting Started](#getting-started)\n  - [Set Up the Router](#set-up-the-router)\n  - [Configure Your Routes](#configure-your-routes)\n  - [Create Links to Your Routes](#create-links-to-your-routes)\n- [Dynamic Routes](#dynamic-routes)\n- [Nested Routes](#nested-routes)\n- [Hash Mode Router](#hash-mode-router)\n- [Memory Mode Router](#memory-mode-router)\n- [Data APIs](#data-apis)\n- [Config Based Routing](#config-based-routing)\n- [Components](#components)\n- [Router Primitives](#router-primitives)\n  - [useParams](#useparams)\n  - [useNavigate](#usenavigate)\n  - [useLocation](#uselocation)\n  - [useSearchParams](#usesearchparams)\n  - [useIsRouting](#useisrouting)\n  - [useMatch](#usematch)\n  - [useCurrentMatches](#useCurrentMatches)\n  - [useBeforeLeave](#usebeforeleave)\n- [SPAs in Deployed Environments](#spas-in-deployed-environments)\n\n## Getting Started\n\n### Set Up the Router\n\n```sh\n> npm i @solidjs/router\n```\n\nInstall `@solidjs/router`, then start your application by rendering the router component\n\n```jsx\nimport { render } from \"solid-js/web\";\nimport { Router } from \"@solidjs/router\";\n\nrender(\n  () => <Router />,\n  document.getElementById(\"app\")\n);\n```\n\nThis sets up a Router that will match on the url to display the desired page\n\n### Configure Your Routes\n\nSolid Router allows you to configure your routes using JSX:\n\n1. Add each route to a `<Router>` using the `Route` component, specifying a path and a component to render when the user navigates to that path.\n\n```jsx\nimport { render } from \"solid-js/web\";\nimport { Router, Route } from \"@solidjs/router\";\n\nimport Home from \"./pages/Home\";\nimport Users from \"./pages/Users\";\n\nrender(() => (\n  <Router>\n    <Route path=\"/users\" component={Users} />\n    <Route path=\"/\" component={Home} />\n  </Router>\n), document.getElementById(\"app\"));\n```\n2. Provide a root level layout\n\nThis will always be there and won't update on page change. It is the ideal place to put top level navigation and Context Providers\n\n```jsx\nimport { render } from \"solid-js/web\";\nimport { Router, Route } from \"@solidjs/router\";\n\nimport Home from \"./pages/Home\";\nimport Users from \"./pages/Users\";\n\nconst App = props => (\n  <>\n    <h1>My Site with lots of pages</h1>\n    {props.children}\n  </>\n)\n\nrender(() => (\n  <Router root={App}>\n    <Route path=\"/users\" component={Users} />\n    <Route path=\"/\" component={Home} />\n  </Router>\n), document.getElementById(\"app\"));\n```\n\n3. Create a CatchAll Route (404 page)\n\nWe can create catchall routes for pages not found at any nested level of the router. We use `*` and optionally the name of a parameter to retrieve the rest of the path.\n\n```jsx\nimport { render } from \"solid-js/web\";\nimport { Router, Route } from \"@solidjs/router\";\n\nimport Home from \"./pages/Home\";\nimport Users from \"./pages/Users\";\nimport NotFound from \"./pages/404\";\n\nconst App = props => (\n  <>\n    <h1>My Site with lots of pages</h1>\n    {props.children}\n  </>\n)\n\nrender(() => (\n  <Router root={App}>\n    <Route path=\"/users\" component={Users} />\n    <Route path=\"/\" component={Home} />\n    <Route path=\"*404\" component={NotFound} />\n  </Router>\n), document.getElementById(\"app\"));\n```\n\n4. Lazy-load route components\n\nThis way, the `Users` and `Home` components will only be loaded if you're navigating to `/users` or `/`, respectively.\n\n```jsx\nimport { lazy } from \"solid-js\";\nimport { render } from \"solid-js/web\";\nimport { Router, Route } from \"@solidjs/router\";\n\nconst Users = lazy(() => import(\"./pages/Users\"));\nconst Home = lazy(() => import(\"./pages/Home\"));\n\nconst App = props => (\n  <>\n    <h1>My Site with lots of pages</h1>\n    {props.children}\n  </>\n)\n\nrender(() => (\n  <Router root={App}>\n    <Route path=\"/users\" component={Users} />\n    <Route path=\"/\" component={Home} />\n  </Router>\n), document.getElementById(\"app\"));\n```\n\n### Create Links to Your Routes\n\nUse an anchor tag that takes you to a route:\n\n```jsx\nimport { lazy } from \"solid-js\";\nimport { render } from \"solid-js/web\";\nimport { Router, Route } from \"@solidjs/router\";\n\nconst Users = lazy(() => import(\"./pages/Users\"));\nconst Home = lazy(() => import(\"./pages/Home\"));\n\nconst App = props => (\n  <>\n    <nav>\n      <a href=\"/about\">About</a>\n      <a href=\"/\">Home</a>\n    </nav>\n    <h1>My Site with lots of pages</h1>\n    {props.children}\n  </>\n);\n\nrender(() => (\n  <Router root={App}>\n    <Route path=\"/users\" component={Users} />\n    <Route path=\"/\" component={Home} />\n  </Router>\n), document.getElementById(\"app\"));\n```\n\n## Dynamic Routes\n\nIf you don't know the path ahead of time, you might want to treat part of the path as a flexible parameter that is passed on to the component.\n\n```jsx\nimport { lazy } from \"solid-js\";\nimport { render } from \"solid-js/web\";\nimport { Router, Route } from \"@solidjs/router\";\n\nconst Users = lazy(() => import(\"./pages/Users\"));\nconst User = lazy(() => import(\"./pages/User\"));\nconst Home = lazy(() => import(\"./pages/Home\"));\n\nrender(() => (\n  <Router>\n    <Route path=\"/users\" component={Users} />\n    <Route path=\"/users/:id\" component={User} />\n    <Route path=\"/\" component={Home} />\n  </Router>\n ), document.getElementById(\"app\"));\n```\n\nThe colon indicates that `id` can be any string, and as long as the URL fits that pattern, the `User` component will show.\n\nYou can then access that `id` from within a route component with `useParams`.\n\n**Note on Animation/Transitions**:\nRoutes that share the same path match will be treated as the same route. If you want to force re-render you can wrap your component in a keyed `<Show>` like:\n```jsx\n<Show when={params.something} keyed><MyComponent></Show>\n```\n---\n\nEach path parameter can be validated using a `MatchFilter`.\nThis allows for more complex routing descriptions than just checking the presence of a parameter.\n\n```jsx\nimport { lazy } from \"solid-js\";\nimport { render } from \"solid-js/web\";\nimport { Router, Route } from \"@solidjs/router\";\nimport type { SegmentValidators } from \"./types\";\n\nconst User = lazy(() => import(\"./pages/User\"));\n\nconst filters: MatchFilters = {\n  parent: [\"mom\", \"dad\"], // allow enum values\n  id: /^\\d+$/, // only allow numbers\n  withHtmlExtension: (v: string) => v.length > 5 && v.endsWith(\".html\"), // we want an `*.html` extension\n};\n\nrender(() => (\n  <Router>\n    <Route\n      path=\"/users/:parent/:id/:withHtmlExtension\"\n      component={User}\n      matchFilters={filters}\n    />\n  </Router>\n), document.getElementById(\"app\"));\n```\n\nHere, we have added the `matchFilters` prop. This allows us to validate the `parent`, `id` and `withHtmlExtension` parameters against the filters defined in `filters`.\nIf the validation fails, the route will not match.\n\nSo in this example:\n\n- `/users/mom/123/contact.html` would match,\n- `/users/dad/123/about.html` would match,\n- `/users/aunt/123/contact.html` would not match as `:parent` is not 'mom' or 'dad',\n- `/users/mom/me/contact.html` would not match as `:id` is not a number,\n- `/users/dad/123/contact` would not match as `:withHtmlExtension` is missing `.html`.\n\n---\n\n### Optional Parameters\n\nParameters can be specified as optional by adding a question mark to the end of the parameter name:\n\n```jsx\n// Matches stories and stories/123 but not stories/123/comments\n<Route path=\"/stories/:id?\" component={Stories} />\n```\n\n### Wildcard Routes\n\n`:param` lets you match an arbitrary name at that point in the path. You can use `*` to match any end of the path:\n\n```jsx\n// Matches any path that begins with foo, including foo/, foo/a/, foo/a/b/c\n<Route path=\"foo/*\" component={Foo} />\n```\n\nIf you want to expose the wild part of the path to the component as a parameter, you can name it:\n\n```jsx\n<Route path=\"foo/*any\" component={Foo} />\n```\n\nNote that the wildcard token must be the last part of the path; `foo/*any/bar` won't create any routes.\n\n### Multiple Paths\n\nRoutes also support defining multiple paths using an array. This allows a route to remain mounted and not rerender when switching between two or more locations that it matches:\n\n```jsx\n// Navigating from login to register does not cause the Login component to re-render\n<Route path={[\"login\", \"register\"]} component={Login} />\n```\n\n## Nested Routes\n\nThe following two route definitions have the same result:\n\n```jsx\n<Route path=\"/users/:id\" component={User} />\n```\n\n```jsx\n<Route path=\"/users\">\n  <Route path=\"/:id\" component={User} />\n</Route>\n```\n\n`/users/:id` renders the `<User/>` component, and `/users/` is an empty route.\n\nOnly leaf Route nodes (innermost `Route` components) are given a route. If you want to make the parent its own route, you have to specify it separately:\n\n```jsx\n//This won't work the way you'd expect\n<Route path=\"/users\" component={Users}>\n  <Route path=\"/:id\" component={User} />\n</Route>\n\n// This works\n<Route path=\"/users\" component={Users} />\n<Route path=\"/users/:id\" component={User} />\n\n// This also works\n<Route path=\"/users\">\n  <Route path=\"/\" component={Users} />\n  <Route path=\"/:id\" component={User} />\n</Route>\n```\n\nYou can also take advantage of nesting by using `props.children` passed to the route component.\n\n```jsx\nfunction PageWrapper(props) {\n  return (\n    <div>\n      <h1> We love our users! </h1>\n      {props.children}\n      <A href=\"/\">Back Home</A>\n    </div>\n  );\n}\n\n<Route path=\"/users\" component={PageWrapper}>\n  <Route path=\"/\" component={Users} />\n  <Route path=\"/:id\" component={User} />\n</Route>;\n```\n\nThe routes are still configured the same, but now the route elements will appear inside the parent element where the `props.children` was declared.\n\nYou can nest indefinitely - just remember that only leaf nodes will become their own routes. In this example, the only route created is `/layer1/layer2`, and it appears as three nested divs.\n\n```jsx\n<Route\n  path=\"/\"\n  component={(props) =>\n    <div>\n      Onion starts here {props.children}\n    </div>\n  }\n>\n  <Route\n    path=\"layer1\"\n    component={(props) =>\n      <div>\n        Another layer {props.children}\n      </div>\n    }\n  >\n    <Route\n      path=\"layer2\"\n      component={() => <div>Innermost layer</div>}\n    />\n  </Route>\n</Route>\n```\n\n## Preload Functions\n\nEven with smart caches it is possible that we have waterfalls both with view logic and with lazy loaded code. With preload functions, we can instead start fetching the data parallel to loading the route, so we can use the data as soon as possible. The preload function is called when the Route is loaded or eagerly when links are hovered.\n\nAs its only argument, the preload function is passed an object that you can use to access route information:\n\n```js\nimport { lazy } from \"solid-js\";\nimport { Route } from \"@solidjs/router\";\n\nconst User = lazy(() => import(\"./pages/users/[id].js\"));\n\n// preload function\nfunction preloadUser({params, location}) {\n  // do preloading\n}\n\n// Pass it in the route definition\n<Route path=\"/users/:id\" component={User} preload={preloadUser} />;\n```\n\n| key      | type                                              | description                                                                                                                   |\n| -------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |\n| params   | object                                            | The route parameters (same value as calling `useParams()` inside the route component)                                         |\n| location | `{ pathname, search, hash, query, state, key}`    | An object that you can use to get more information about the path (corresponds to [`useLocation()`](#uselocation))        |\n| intent | `\"initial\", \"navigate\", \"native\", \"preload\"` | Indicates why this function is being called. <ul><li>\"initial\" - the route is being initially shown (ie page load)</li><li>\"native\" - navigate originated from the browser (eg back/forward)</li><li>\"navigate\" - navigate originated from the router (eg call to navigate or anchor clicked)</li><li>\"preload\" - not navigating, just preloading (eg link hover)</li></ul> |\n\n\nA common pattern is to export the preload function and data wrappers that corresponds to a route in a dedicated `route.data.js` file. This way, the data function can be imported without loading anything else.\n\n```js\nimport { lazy } from \"solid-js\";\nimport { Route } from \"@solidjs/router\";\nimport preloadUser from \"./pages/users/[id].data.js\";\nconst User = lazy(() => import(\"/pages/users/[id].js\"));\n\n// In the Route definition\n<Route path=\"/users/:id\" component={User} preload={preloadUser} />;\n```\n\nThe return value of the `preload` function is passed to the page component when called at anytime other than `\"preload\"` intent, so you can initialize things in there, or alternatively use our new Data APIs:\n\n\n## Data APIs\n\nKeep in mind these are completely optional. To use but showcase the power of our preload mechanism.\n\n### `query`\n\nTo prevent duplicate fetching and to trigger handle refetching we provide a query api. That takes a function and returns the same function.\n\n```jsx\nconst getUser = query(async (id) => {\n  return (await fetch(`/api/users${id}`)).json()\n}, \"users\") // used as the query key + serialized arguments\n```\nIt is expected that the arguments to the query function are serializable.\n\nThis query accomplishes the following:\n\n1. It does deduping on the server for the lifetime of the request.\n2. It fills a preload cache in the browser which lasts 5 seconds. When a route is preloaded on hover or when preload is called when entering a route it will make sure to dedupe calls.\n3. We have a reactive refetch mechanism based on key. So we can tell routes that aren't new to retrigger on action revalidation.\n4. It will serve as a back/forward cache for browser navigation up to 5 mins. Any user based navigation or link click bypasses this cache. Revalidation or new fetch updates the cache.\n\nUsing it with preload function might look like:\n\n```js\nimport { lazy } from \"solid-js\";\nimport { Route } from \"@solidjs/router\";\nimport { getUser } from ... // the query function\n\nconst User = lazy(() => import(\"./pages/users/[id].js\"));\n\n// preload function\nfunction preloadUser({params, location}) {\n  void getUser(params.id)\n}\n\n// Pass it in the route definition\n<Route path=\"/users/:id\" component={User} preload={preloadUser} />;\n```\n\nInside your page component you:\n\n```jsx\n// pages/users/[id].js\nimport { getUser } from ... // the query function\n\nexport default function User(props) {\n  const user = createAsync(() => getUser(props.params.id));\n  return <h1>{user().name}</h1>;\n}\n```\n\nCached function has a few useful methods for getting the key that are useful for invalidation.\n```ts\nlet id = 5;\n\ngetUser.key // returns \"users\"\ngetUser.keyFor(id) // returns \"users[5]\"\n```\n\nYou can revalidate the query using the `revalidate` method or you can set `revalidate` keys on your response from your actions. If you pass the whole key it will invalidate all the entries for the query (ie \"users\" in the example above). You can also invalidate a single entry by using `keyFor`.\n\n`query` can be defined anywhere and then used inside your components with:\n\n### `createAsync`\n\nThis is light wrapper over `createResource` that aims to serve as stand-in for a future primitive we intend to bring to Solid core in 2.0. It is a simpler async primitive where the function tracks like `createMemo` and it expects a promise back that it turns into a Signal. Reading it before it is ready causes Suspense/Transitions to trigger.\n\n```jsx\nconst user = createAsync((currentValue) => getUser(params.id))\n```\n\nIt also preserves `latest` field from `createResource`. Note that it will be removed in the future.\n\n```jsx\nconst user = createAsync((currentValue) => getUser(params.id))\nreturn <h1>{user.latest.name}</h1>;\n```\n\nUsing `query` in `createResource` directly won't work properly as the fetcher is not reactive and it won't invalidate properly.\n\n### `createAsyncStore`\n\nSimilar to `createAsync` except it uses a deeply reactive store. Perfect for applying fine-grained changes to large model data that updates.\nIt also supports `latest` field which will be removed in the future.\n\n```jsx\nconst todos = createAsyncStore(() => getTodos());\n```\n\n### `action`\n\nActions are data mutations that can trigger invalidations and further routing. A list of prebuilt response helpers can be found below.\n```jsx\nimport { action, revalidate, redirect } from \"@solidjs/router\"\n\n// anywhere\nconst myAction = action(async (data) => {\n  await doMutation(data);\n  throw redirect(\"/\", { revalidate: getUser.keyFor(data.id) }); // throw a response to do a redirect\n});\n\n// in component\n<form action={myAction} method=\"post\" />\n\n//or\n<button type=\"submit\" formaction={myAction}></button>\n```\n\nActions only work with post requests, so make sure to put `method=\"post\"` on your form.\n\nSometimes it might be easier to deal with typed data instead of `FormData` and adding additional hidden fields. For that reason Actions have a with method. That works similar to `bind` which applies the arguments in order.\n\nPicture an action that deletes Todo Item:\n\n```js\nconst deleteTodo = action(async (formData: FormData) => {\n  const id = Number(formData.get(\"id\"))\n  await api.deleteTodo(id)\n})\n\n<form action={deleteTodo} method=\"post\">\n  <input type=\"hidden\" name=\"id\" value={todo.id} />\n  <button type=\"submit\">Delete</button>\n</form>\n```\nInstead with `with` you can write this:\n```js\nconst deleteUser = action(api.deleteTodo)\n\n<form action={deleteTodo.with(todo.id)} method=\"post\">\n  <button type=\"submit\">Delete</button>\n</form>\n```\n\nActions also a second argument which can be the name or an option object with `name` and `onComplete`. `name` is used to identify SSR actions that aren't server functions (see note below). `onComplete` allows you to configure behavior when `action`s complete. Keep in mind `onComplete` does not work when JavaScript is disabled.\n\n#### Notes on `<form>` implementation and SSR\nThis requires stable references as you can only serialize a string as an attribute, and across SSR they'd need to match. The solution is providing a unique name.\n\n```jsx\nconst myAction = action(async (args) => {}, \"my-action\");\n```\n\n### `useAction`\n\nInstead of forms you can use actions directly by wrapping them in a `useAction` primitive. This is how we get the router context.\n\n```jsx\n// in component\nconst submit = useAction(myAction)\nsubmit(...args)\n```\n\nThe outside of a form context you can use custom data instead of formData, and these helpers preserve types. However, even when used with server functions (in projects like SolidStart) this requires client side javascript and is not Progressive Enhancible like forms are.\n\n### `useSubmission`/`useSubmissions`\n\nAre used to injecting the optimistic updates while actions are in flight. They either return a single Submission(latest) or all that match with an optional filter function.\n\n```jsx\ntype Submission<T, U> = {\n  readonly input: T;\n  readonly result?: U;\n  readonly pending: boolean;\n  readonly url: string;\n  clear: () => void;\n  retry: () => void;\n};\n\nconst submissions = useSubmissions(action, (input) => filter(input));\nconst submission = useSubmission(action, (input) => filter(input));\n```\n\n### Response Helpers\n\nThese are used to communicate router navigations from query/actions, and can include invalidation hints. Generally these are thrown to not interfere the with the types and make it clear that function ends execution at that point.\n\n#### `redirect(path, options)`\n\nRedirects to the next route\n```js\nconst getUser = query(() => {\n  const user = await api.getCurrentUser()\n  if (!user) throw redirect(\"/login\");\n  return user;\n})\n```\n\n#### `reload(options)`\n\nReloads the data on the current page\n```js\nconst getTodo = query(async (id: number) => {\n  const todo = await fetchTodo(id);\n  return todo;\n}, \"todo\")\n\nconst updateTodo = action(async (todo: Todo) => {\n  await updateTodo(todo.id, todo);\n  reload({ revalidate: getTodo.keyFor(id) })\n})\n```\n\n## Config Based Routing\n\nYou don't have to use JSX to set up your routes; you can pass an array of route definitions:\n\n```jsx\nimport { lazy } from \"solid-js\";\nimport { render } from \"solid-js/web\";\nimport { Router } from \"@solidjs/router\";\n\nconst routes = [\n  {\n    path: \"/users\",\n    component: lazy(() => import(\"/pages/users.js\")),\n  },\n  {\n    path: \"/users/:id\",\n    component: lazy(() => import(\"/pages/users/[id].js\")),\n    children: [\n      {\n        path: \"/\",\n        component: lazy(() => import(\"/pages/users/[id]/index.js\")),\n      },\n      {\n        path: \"/settings\",\n        component: lazy(() => import(\"/pages/users/[id]/settings.js\")),\n      },\n      {\n        path: \"/*all\",\n        component: lazy(() => import(\"/pages/users/[id]/[...all].js\")),\n      },\n    ],\n  },\n  {\n    path: \"/\",\n    component: lazy(() => import(\"/pages/index.js\")),\n  },\n  {\n    path: \"/*all\",\n    component: lazy(() => import(\"/pages/[...all].js\")),\n  },\n];\n\nrender(() =>\n  <Router>{routes}</Router>,\n  document.getElementById(\"app\")\n);\n```\n\nAlso you can pass a single route definition object for a single route:\n\n```jsx\nimport { lazy } from \"solid-js\";\nimport { render } from \"solid-js/web\";\nimport { Router } from \"@solidjs/router\";\n\nconst route = {\n  path: \"/\",\n  component: lazy(() => import(\"/pages/index.js\"))\n};\n\nrender(() => <Router>{route}</Router>, document.getElementById(\"app\"));\n```\n\n## Alternative Routers\n\n### Hash Mode Router\n\nBy default, Solid Router uses `location.pathname` as route path. You can simply switch to hash mode through using `<HashRouter>`.\n\n```jsx\nimport { HashRouter } from \"@solidjs/router\";\n\n<HashRouter />;\n```\n\n### Memory Mode Router\n\nYou can also use memory mode router for testing purpose.\n\n```jsx\nimport { MemoryRouter } from \"@solidjs/router\";\n\n<MemoryRouter />;\n```\n\n### SSR Routing\n\nFor SSR you can use the static router directly or the browser Router defaults to it on the server, just pass in the url.\n\n```jsx\nimport { isServer } from \"solid-js/web\";\nimport { Router } from \"@solidjs/router\";\n\n<Router url={isServer ? req.url : \"\"} />;\n```\n\n\n## Components\n\n### `<Router>`\n\nThis is the main Router component for the browser.\n\n| prop | type | description |\n|-----|----|----|\n| children | `JSX.Element`, `RouteDefinition`, or `RouteDefinition[]` | The route definitions |\n| root | Component | Top level layout component |\n| base | string | Base url to use for matching routes |\n| actionBase | string | Root url for server actions, default: `/_server` |\n| preload | boolean | Enables/disables preloads globally, default: `true` |\n| explicitLinks | boolean | Disables all anchors being intercepted and instead requires `<A>`. Default: `false`. (To disable interception for a specific link, set `target` to any value, e.g. `<a target=\"_self\">`.) |\n\n### `<A>`\n\nLike the `<a>` tag but supports automatic apply of base path + relative paths and active class styling (requires client side JavaScript).\n\nThe `<A>` tag has an `active` class if its href matches the current location, and `inactive` otherwise. **Note:** By default matching includes locations that are descendents (eg. href `/users` matches locations `/users` and `/users/123`), use the boolean `end` prop to prevent matching these. This is particularly useful for links to the root route `/` which would match everything.\n\n| prop          |  type   | description                                                                                                                                                                              |\n| ------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| href          | string  | The path of the route to navigate to. This will be resolved relative to the route that the link is in, but you can preface it with `/` to refer back to the root.                        |\n| noScroll      | boolean | If true, turn off the default behavior of scrolling to the top of the new page                                                                                                           |\n| replace       | boolean | If true, don't add a new entry to the browser history. (By default, the new page will be added to the browser history, so pressing the back button will take you to the previous route.) |\n| state         | unknown | [Push this value](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) to the history stack when navigating                                                               |\n| inactiveClass | string  | The class to show when the link is inactive (when the current location doesn't match the link)                                                                                           |\n| activeClass   | string  | The class to show when the link is active                                                                                                                                                |\n| end           | boolean | If `true`, only considers the link to be active when the curent location matches the `href` exactly; if `false`, check if the current location _starts with_ `href`                      |\n\n### `<Navigate />`\n\nSolid Router provides a `Navigate` component that works similarly to `A`, but it will _immediately_ navigate to the provided path as soon as the component is rendered. It also uses the `href` prop, but you have the additional option of passing a function to `href` that returns a path to navigate to:\n\n```jsx\nfunction getPath({ navigate, location }) {\n  // navigate is the result of calling useNavigate(); location is the result of calling useLocation().\n  // You can use those to dynamically determine a path to navigate to\n  return \"/some-path\";\n}\n\n// Navigating to /redirect will redirect you to the result of getPath\n<Route path=\"/redirect\" component={() => <Navigate href={getPath} />} />;\n```\n\n### `<Route>`\n\nThe Component for defining Routes:\n\n| prop | type | description |\n|-|-|-|\n| path | string | Path partial for defining the route segment |\n| component | `Component` | Component that will be rendered for the matched segment |\n| matchFilters | `MatchFilters` | Additional constraints for matching against the route |\n| children | `JSX.Element` | Nested `<Route>` definitions |\n| preload | `RoutePreloadFunc` | Function called during preload or when the route is navigated to. |\n\n## Router Primitives\n\nSolid Router provides a number of primitives that read off the Router and Route context.\n\n### useParams\n\nRetrieves a reactive, store-like object containing the current route path parameters as defined in the Route.\n\n```js\nconst params = useParams();\n\n// fetch user based on the id path parameter\nconst [user] = createResource(() => params.id, fetchUser);\n```\n\n### useNavigate\n\nRetrieves method to do navigation. The method accepts a path to navigate to and an optional object with the following options:\n\n- resolve (_boolean_, default `true`): resolve the path against the current route\n- replace (_boolean_, default `false`): replace the history entry\n- scroll (_boolean_, default `true`): scroll to top after navigation\n- state (_any_, default `undefined`): pass custom state to `location.state`\n\n**Note:** The state is serialized using the [structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) which does not support all object types.\n\n```js\nconst navigate = useNavigate();\n\nif (unauthorized) {\n  navigate(\"/login\", { replace: true });\n}\n```\n\n### useLocation\n\nRetrieves reactive `location` object useful for getting things like `pathname`\n\n```js\nconst location = useLocation();\n\nconst pathname = createMemo(() => parsePath(location.pathname));\n```\n\n### useSearchParams\n\nRetrieves a tuple containing a reactive object to read the current location's query parameters and a method to update them. The object is a proxy so you must access properties to subscribe to reactive updates. Note values will be strings and property names will retain their casing.\n\nThe setter method accepts an object whose entries will be merged into the current query string. Values `''`, `undefined` and `null` will remove the key from the resulting query string. Updates will behave just like a navigation and the setter accepts the same optional second parameter as `navigate` and auto-scrolling is disabled by default.\n\n```js\nconst [searchParams, setSearchParams] = useSearchParams();\n\nreturn (\n  <div>\n    <span>Page: {searchParams.page}</span>\n    <button\n      onClick={() =>\n        setSearchParams({ page: (parseInt(searchParams.page) || 0) + 1 })\n      }\n    >\n      Next Page\n    </button>\n  </div>\n);\n```\n\n### useIsRouting\n\nRetrieves signal that indicates whether the route is currently in a Transition. Useful for showing stale/pending state when the route resolution is Suspended during concurrent rendering.\n\n```js\nconst isRouting = useIsRouting();\n\nreturn (\n  <div classList={{ \"grey-out\": isRouting() }}>\n    <MyAwesomeContent />\n  </div>\n);\n```\n\n### useMatch\n\n`useMatch` takes an accessor that returns the path and creates a Memo that returns match information if the current path matches the provided path. Useful for determining if a given path matches the current route.\n\n```js\nconst match = useMatch(() => props.href);\n\nreturn <div classList={{ active: Boolean(match()) }} />;\n```\n\n### useCurrentMatches\n\n`useCurrentMatches` returns all the matches for the current matched route. Useful for getting all the route information.\n\nFor example if you stored breadcrumbs on your route definition you could retrieve them like so:\n```js\nconst matches = useCurrentMatches();\nconst breadcrumbs = createMemo(() => matches().map(m => m.route.info.breadcrumb))\n```\n\n### usePreloadRoute\n\n`usePreloadRoute` returns a function that can be used to preload a route manual. This is what happens automatically with link hovering and similar focus based behavior, but it is available here as an API.\n\n```js\nconst preload = usePreloadRoute();\n\npreload(`/users/settings`, { preloadData: true });\n```\n\n### useBeforeLeave\n\n`useBeforeLeave` takes a function that will be called prior to leaving a route. The function will be called with:\n\n- from (_Location_): current location (before change).\n- to (_string | number_}: path passed to `navigate`.\n- options (_NavigateOptions_}: options passed to `navigate`.\n- preventDefault (_void function_): call to block the route change.\n- defaultPrevented (_readonly boolean_): true if any previously called leave handlers called preventDefault().\n- retry (_void function_, _force?: boolean_ ): call to retry the same navigation, perhaps after confirming with the user. Pass `true` to skip running the leave handlers again (ie force navigate without confirming).\n\nExample usage:\n\n```js\nuseBeforeLeave((e: BeforeLeaveEventArgs) => {\n  if (form.isDirty && !e.defaultPrevented) {\n    // preventDefault to block immediately and prompt user async\n    e.preventDefault();\n    setTimeout(() => {\n      if (window.confirm(\"Discard unsaved changes - are you sure?\")) {\n        // user wants to proceed anyway so retry with force=true\n        e.retry(true);\n      }\n    }, 100);\n  }\n});\n```\n\n## Migrations from 0.9.x\n\nv0.10.0 brings some big changes to support the future of routing including Islands/Partial Hydration hybrid solutions. Most notably there is no Context API available in non-hydrating parts of the application.\n\nThe biggest changes are around removed APIs that need to be replaced.\n\n### `<Outlet>`, `<Routes>`, `useRoutes`\n\nThis is no longer used and instead will use `props.children` passed from into the page components for outlets. This keeps the outlet directly passed from its page and avoids oddness of trying to use context across Islands boundaries. Nested `<Routes>` components inherently cause waterfalls and are `<Outlets>` themselves so they have the same concerns.\n\nKeep in mind no `<Routes>` means the `<Router>` API is different. The `<Router>` acts as the `<Routes>` component and its children can only be `<Route>` components. Your top-level layout should go in the root prop of the router [as shown above](#configure-your-routes)\n\n## `element` prop removed from `Route`\n\nRelated without Outlet component it has to be passed in manually. At which point the `element` prop has less value. Removing the second way to define route components to reduce confusion and edge cases.\n\n### `data` functions & `useRouteData`\n\nThese have been replaced by a preload mechanism. This  allows link hover preloads (as the preload function can be run as much as wanted without worry about reactivity). It support deduping/query APIs which give more control over how things are cached. It also addresses TS issues with getting the right types in the Component without `typeof` checks.\n\nThat being said you can reproduce the old pattern largely by turning off preloads at the router level and then injecting your own Context:\n\n```js\nimport { lazy } from \"solid-js\";\nimport { Route } from \"@solidjs/router\";\n\nconst User = lazy(() => import(\"./pages/users/[id].js\"));\n\n// preload function\nfunction preloadUser({params, location}) {\n  const [user] = createResource(() => params.id, fetchUser);\n  return user;\n}\n\n// Pass it in the route definition\n<Router preload={false}>\n  <Route path=\"/users/:id\" component={User} preload={preloadUser} />\n</Router>\n```\n\nAnd then in your component taking the page props and putting them in a Context.\n```js\nfunction User(props) {\n  <UserContext.Provider value={props.data}>\n    {/* my component content  */}\n  </UserContext.Provider>\n}\n\n// Somewhere else\nfunction UserDetails() {\n  const user = useContext(UserContext)\n  // render stuff\n}\n```\n\n## SPAs in Deployed Environments\n\nWhen deploying applications that use a client side router that does not rely on Server Side Rendering you need to handle redirects to your index page so that loading from other URLs does not cause your CDN or Hosting to return not found for pages that aren't actually there.\n\nEach provider has a different way of doing this. For example on Netlify you create a `_redirects` file that contains:\n\n```sh\n/*   /index.html   200\n```\n\nOn Vercel you add a rewrites section to your `vercel.json`:\n\n```json\n{\n  \"rewrites\": [\n    {\n      \"source\": \"/(.*)\",\n      \"destination\": \"/index.html\"\n    }\n  ]\n}\n```\n","readmeFilename":"README.md"}