### Install nuqs-svelte with pnpm, yarn, or npm Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md These commands show how to install the nuqs-svelte package using different package managers. Ensure you have one of them installed to manage your project's dependencies. ```shell pnpm add nuqs-svelte ``` ```shell yarn add nuqs-svelte ``` ```shell npm install nuqs-svelte ``` -------------------------------- ### SvelteKit Adapter Setup for nuqs-svelte Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md This Svelte component demonstrates how to integrate nuqs-svelte with SvelteKit by wrapping the application's children with the NuqsAdapter. This is necessary for routing and state management to function correctly within a SvelteKit project. ```svelte // src/routes/+layout.svelte {@render children()} ``` -------------------------------- ### Creating Custom Parsers in TypeScript Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Illustrates how to create custom parsers using createParser and compose them with existing parsers. This example creates a hex color parser that parses RGB values from a 6-character hex string. The parser can be configured with common options like history behavior. ```typescript import { createParser, parseAsHex } from "nuqs-svelte"; // Wrapping your parser/serializer in `createParser` // gives it access to the builder pattern & server-side // parsing capabilities: const hexColorSchema = createParser({ parse(query) { if (query.length !== 6) { return null; // always return null for invalid inputs } return { // When composing other parsers, they may return null too. r: parseAsHex.parse(query.slice(0, 2)) ?? 0x00, g: parseAsHex.parse(query.slice(2, 4)) ?? 0x00, b: parseAsHex.parse(query.slice(4)) ?? 0x00, }; }, serialize({ r, g, b }) { return parseAsHex.serialize(r) + parseAsHex.serialize(g) + parseAsHex.serialize(b); }, }) // Eg: set common options directly .withOptions({ history: "push" }); // Or on usage: useQueryState( "tribute", hexColorSchema.withDefault({ r: 0x66, g: 0x33, b: 0x99, }), ); ``` -------------------------------- ### Generate Dynamic Canonical URL with Query String Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md When query strings define page content (e.g., video URLs), the canonical URL should include relevant parameters. This example shows how to dynamically generate a canonical URL using `generateMetadata` and `useQueryState` in Next.js. ```typescript // page.tsx import type { Metadata, ResolvingMetadata } from "next"; import { useQueryState } from "nuqs"; import { parseAsString } from "nuqs/server"; type Props = { searchParams: { [key: string]: string | string[] | undefined }; }; export async function generateMetadata({ searchParams }: Props): Promise { const videoId = parseAsString.parseServerSide(searchParams.v); return { alternates: { canonical: `/watch?v=${videoId}`, }, }; } ``` -------------------------------- ### Configuring Parsers with Builder Pattern in TypeScript Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Shows how to use the builder pattern to configure parsers with default values and options. This example uses parseAsInteger with a default value of 0 and history option set to 'push'. Custom parsers can also be created and composed with existing ones. ```typescript useQueryState( "counter", parseAsInteger.withDefault(0).withOptions({ history: "push", shallow: false, }), ); ``` -------------------------------- ### Awaiting Query State Updates in TypeScript Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Shows how to await the Promise returned by state updater functions to get the updated URLSearchParams object. This allows you to know when the URL has been updated and access the current parameter values. Batched updates are merged and flushed once to the URL. ```typescript const randomCoordinates = () => { setLat(42); return setLng(12); }; randomCoordinates().then((search: URLSearchParams) => { search.get("lat"); // 42 search.get("lng"); // 12, has been queued and batch-updated }); ``` -------------------------------- ### Nuqs Shareable Parsers for Client and Server Components Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Illustrates sharing parser definitions between server and client components using 'nuqs/server'. It demonstrates accessing all parameters or individual ones in server components and using 'useQueryStates' in client components. ```tsx // searchParams.ts import { parseAsFloat, createSearchParamsCache } from "nuqs/server"; export const coordinatesParsers = { lat: parseAsFloat.withDefault(45.18), lng: parseAsFloat.withDefault(5.72), }; export const coordinatesCache = createSearchParamsCache(coordinatesParsers); // page.tsx import { coordinatesCache } from "./searchParams"; import { Server } from "./server"; import { Client } from "./client"; export default async function Page({ searchParams }) { await coordinatesCache.parse(searchParams); return ( <> ); } // server.tsx import { coordinatesCache } from "./searchParams"; export function Server() { const { lat, lng } = coordinatesCache.all(); // or access keys individually: const lat = coordinatesCache.get("lat"); const lng = coordinatesCache.get("lng"); return ( Latitude: {lat} - Longitude: {lng} ); } // client.tsx // prettier-ignore 'use client' import { useQueryStates } from "nuqs"; import { coordinatesParsers } from "./searchParams"; export function Client() { const [{ lat, lng }, setCoordinates] = useQueryStates(coordinatesParsers); // ... } ``` -------------------------------- ### Unit Test Components with `NuqsTestingAdapter` Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md The `NuqsTestingAdapter` allows for isolated unit testing of components that use `useQueryState` or `useQueryStates`. It integrates with testing frameworks like Vitest and Testing Library, enabling mocking of initial search parameters and capturing URL update events. ```tsx import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { NuqsTestingAdapter, type UrlUpdateEvent } from "nuqs/adapters/testing"; import { describe, expect, it, vi } from "vitest"; import { CounterButton } from "./counter-button"; it("should increment the count when clicked", async () => { const user = userEvent.setup(); const onUrlUpdate = vi.fn<[UrlUpdateEvent]>(); render(, { // Setup the test by passing initial search params / querystring, // and give it a function to call on URL updates wrapper: ({ children }) => ( {children} ), }); // Initial state assertions: there's a clickable button displaying the count const button = screen.getByRole("button"); expect(button).toHaveTextContent("count is 42"); // Act await user.click(button); // Assert changes in the state and in the (mocked) URL expect(button).toHaveTextContent("count is 43"); expect(onUrlUpdate).toHaveBeenCalledOnce(); expect(onUrlUpdate.mock.calls[0][0].queryString).toBe("?count=43"); expect(onUrlUpdate.mock.calls[0][0].searchParams.get("count")).toBe("43"); expect(onUrlUpdate.mock.calls[0][0].options.history).toBe("push"); }); ``` -------------------------------- ### Nuqs Serializer Helper for Link Generation Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Explains how to use the 'createSerializer' helper from 'nuqs/server' to generate query strings for URL parameters. It allows defining search param structures and serializing values into a query string format compatible with nuqs hooks. ```ts import { createSerializer, parseAsInteger, parseAsIsoDateTime, parseAsString, parseAsStringLiteral, } from "nuqs/server"; const searchParams = { search: parseAsString, limit: parseAsInteger, from: parseAsIsoDateTime, to: parseAsIsoDateTime, sortBy: parseAsStringLiteral(["asc", "desc"] as const), }; // Create a serializer function by passing the description of the search params to accept const serialize = createSerializer(searchParams); // Then later, pass it some values (a subset) and render them to a query string serialize({ search: "foo bar", limit: 10, from: new Date("2024-01-01"), // here, we omit `to`, which won't be added sortBy: null, // null values are also not rendered }); // ?search=foo+bar&limit=10&from=2024-01-01T00:00:00.000Z ``` -------------------------------- ### Create Custom Query Parsers with Serialization and Equality (Svelte) Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Shows how to create custom query string parsers using `createParser` from `nuqs-svelte`. This allows full control over parsing, serialization, and equality checking for complex data types. ```svelte

Hex: #{hexString}

``` -------------------------------- ### Create One-Off Search Param Loader with Nuqs Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Demonstrates how to create a loader function using 'nuqs' to parse search parameters from a URL string. It supports various input types and allows defining default values for parameters. ```tsx import { createLoader } from "nuqs"; // or 'nuqs/server' const searchParams = { q: parseAsString, page: parseAsInteger.withDefault(1), }; const loadSearchParams = createLoader(searchParams); const { q, page } = loadSearchParams("?q=hello&page=2"); ``` -------------------------------- ### Implement Integer Query State Parsing with Pagination in Svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Parses URL query parameters as integers for pagination using parseAsInteger. Uses useQueryState hook with default values for page and limit. Calculates offset reactively and provides next/previous page navigation with history push. ```svelte

Page {page.current} | Showing {limit.current} items

Offset: {offset}

``` -------------------------------- ### Basic Usage of useQueryState in nuqs-svelte Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md This Svelte component illustrates the fundamental usage of the `useQueryState` hook from nuqs-svelte. It binds an input field to a query parameter named 'name', allowing for two-way data binding between the input's value and the URL's query string. ```svelte // src/routes/+page.svelte

Hello, {name.current || "anonymous visitor"}!

``` -------------------------------- ### Configuring Nuqs-Svelte Options for Behavior Customization Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Demonstrates how to configure URL update behavior at adapter-wide, hook-level, or per-update using various options like history, scroll, throttleMs, and clearOnDefault. ```svelte ``` -------------------------------- ### Manage Single Query Parameter with useQueryState (Svelte) Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Manages a single query parameter in the URL using type-safe parsing and reactivity. It allows setting default values and updating the URL with history management. Dependencies include 'nuqs-svelte' and its parsing functions. ```svelte

Count: {count.current}

``` -------------------------------- ### NuqsAdapter for SvelteKit Integration Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Integrates nuqs-svelte with SvelteKit's routing system. It wraps the application's content and applies specified options for history management, shallow routing, and scrolling behavior. ```svelte {@render children()} ``` ```svelte ``` -------------------------------- ### Manage Multiple Query Parameters with useQueryStates (Svelte) Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Manages multiple related query parameters atomically using 'useQueryStates'. This function allows defining and synchronizing several parameters, such as location coordinates and zoom level, with built-in type safety and configurable update options. Dependencies include 'nuqs-svelte' and its parsing functions. ```svelte
``` -------------------------------- ### NuqsAdapter for Vanilla Svelte Integration Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Integrates nuqs-svelte with vanilla Svelte applications using native browser APIs. This adapter is suitable for any Svelte 5 application not using SvelteKit. ```svelte ``` ```svelte ``` -------------------------------- ### Generate Query Strings Programmatically with Custom Parsers (Svelte) Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Illustrates the use of `createSerializer` from `nuqs-svelte` to generate query strings from values. This is useful for creating navigation links and programmatic URL manipulation. ```svelte ``` -------------------------------- ### Implement Float Query State Parsing for Numeric Ranges in Svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Parses URL query parameters as floating-point numbers using parseAsFloat. Demonstrates price and rating range inputs with reactive tax and total calculations based on price value. ```svelte

Tax: ${tax.toFixed(2)}

Total: ${total.toFixed(2)}

``` -------------------------------- ### Batching Multiple Query Updates in Svelte Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Demonstrates how to perform multiple query state updates in a single event loop tick. The updates are batched and applied asynchronously to the URL. Each state setter function returns a Promise that resolves with the updated URLSearchParams object. ```svelte ``` -------------------------------- ### Handle Invalid Inputs and Errors with nuqs-svelte Parsers Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Demonstrates how nuqs-svelte parsers handle invalid inputs by returning null, and how to use default values or runtime validation with try-catch blocks to manage error scenarios gracefully. This ensures a more robust user experience when dealing with potentially malformed URL query parameters. ```svelte
validateAndSet(e.currentTarget.value)} placeholder="Enter age" /> {#if age.current === null}

Invalid age value in URL

{/if}
``` -------------------------------- ### Batch Multiple State Updates in Svelte with nuqs-svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Demonstrates how nuqs-svelte automatically batches multiple state updates within the same tick into a single URL update, optimizing performance. It also shows how to perform atomic updates for guaranteed single URL changes using `useQueryStates`. ```svelte
{#each cities as city} {/each}
``` -------------------------------- ### Parse ISO DateTime in Svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Demonstrates parsing query parameters as ISO-8601 datetime strings using parseAsIsoDateTime from nuqs-svelte. Implements date range selection with default values and computed duration between dates. Includes UI controls with datetime-local inputs and a button to set the last 7 days range. ```svelte
startDate.current = new Date(e.currentTarget.value)} /> endDate.current = new Date(e.currentTarget.value)} />

Duration: {durationDays} days

``` -------------------------------- ### Using useQueryStates Hook in TypeScript Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Demonstrates how to use the useQueryStates hook for managing multiple related query parameters as a single unit. This approach ensures that related parameters are updated together and provides a convenient way to set multiple keys at once. The hook returns individual state variables and a combined setter function. ```typescript import { useQueryStates, parseAsFloat } from "nuqs-svelte"; const coordinates = useQueryStates( { lat: parseAsFloat.withDefault(45.18), lng: parseAsFloat.withDefault(5.72), }, { history: "push", }, ); const { lat, lng } = coordinates; // Set all (or a subset of) the keys in one go: const search = await coordinates.set({ lat: Math.random() * 180 - 90, lng: Math.random() * 360 - 180, }); ``` -------------------------------- ### Synchronize State Across Svelte Components with nuqs-svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Illustrates how multiple Svelte components can observe and update the same query parameter, ensuring automatic synchronization across the application. This pattern is facilitated by nuqs-svelte's underlying event emitter mechanism, simplifying global state management. ```svelte

Component A: {count.current}

Component B: {count.current}

``` -------------------------------- ### String Query Parameter Parsing with parseAsString (Svelte) Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Provides a string parser for managing query parameters as strings, with support for default values and custom options like history management. This function is part of the 'nuqs-svelte' library and is used with 'useQueryState' or 'useQueryStates'. ```svelte ``` -------------------------------- ### Nuqs Server Component Search Params Cache Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Shows how to use 'nuqs/server' to create a type-safe cache for search parameters within Server Components. It includes parsing search params and accessing them in child components. ```tsx // searchParams.ts import { createSearchParamsCache, parseAsInteger, parseAsString } from "nuqs/server"; // Note: import from 'nuqs/server' to avoid the "use client" directive export const searchParamsCache = createSearchParamsCache({ // List your search param keys and associated parsers here: q: parseAsString.withDefault(""), maxResults: parseAsInteger.withDefault(10), }); // page.tsx import { searchParamsCache } from "./searchParams"; export default function Page({ searchParams, }: { searchParams: Record; }) { // ⚠️ Don't forget to call `parse` here. // You can access type-safe values from the returned object: const { q: query } = searchParamsCache.parse(searchParams); return (

Search Results for {query}

); } function Results() { // Access type-safe search params in children server components: const maxResults = searchParamsCache.get("maxResults"); return Showing up to {maxResults} results; } ``` -------------------------------- ### Parse Arrays in Svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Demonstrates parsing query parameters as arrays using parseAsArrayOf with different element parsers from nuqs-svelte. Shows both string arrays with custom separators and integer arrays. Includes UI components for adding and removing tags dynamically and displaying selected IDs. ```svelte
{#each tags.current as tag} {tag} {/each}

Selected IDs: {ids.current.join(", ")}

``` -------------------------------- ### Enable Debug Logs in Browser Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Debug logs for nuqs can be enabled in the browser's developer console by setting the `debug` item in localStorage to `nuqs`. This provides insights into `useQueryState` and `useQueryStates` operations. Wildcards can be used by combining with other debug flags. ```javascript // In your devtools: localStorage.setItem("debug", "nuqs"); ``` ```javascript // Note: unlike the `debug` package, this will not work with wildcards, but // you can combine it: localStorage.setItem('debug', '*,nuqs') ``` -------------------------------- ### Parse Query Parameters as JSON Objects with Runtime Validation (Svelte) Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Demonstrates how to use `parseAsJson` from `nuqs-svelte` to parse query parameters as JSON-encoded objects. It includes runtime validation using a custom type guard function and provides a default value. ```svelte
{JSON.stringify(filter.current, null, 2)}
``` -------------------------------- ### Implement Boolean Query State Parsing for UI Toggles in Svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Parses URL query parameters as boolean values using parseAsBoolean. Shows dark mode, sidebar visibility, and optional notification settings with toggle functionality and null state handling. ```svelte
``` -------------------------------- ### Implement Hexadecimal Query State Parsing for Color Values in Svelte Source: https://context7.com/rtrampox/nuqs-svelte/llms.txt Parses URL query parameters as hexadecimal integers using parseAsHex. Converts color values between hex, RGB, and decimal formats with a color picker input and reactive transformations. ```svelte
color.current = parseInt(e.currentTarget.value.slice(1), 16)} />

Hex: #{hexString}

RGB: ({rgb.r}, {rgb.g}, {rgb.b})

Decimal: {color.current}

``` -------------------------------- ### Enable Shallow Updates for Query State in Nuqs-Svelte (TypeScript) Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Opt-in to server-side refetches on state updates by setting shallow to false, defaulting to client-only updates. Only works with the SvelteKit adapter. Requires 'nuqs-svelte' and SvelteKit. Inputs are state set calls; outputs trigger network requests for data reloading. Useful for data-dependent pages. ```ts const state = useQueryState("foo", { shallow: false }); // You can also pass the option on calls to setState: state.set("bar", { shallow: false }); ``` -------------------------------- ### Set Default Values for Query State in Svelte (TypeScript) Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Shows how to handle null states by setting default values on parsers, illustrated with a counter component that avoids manual null checks. By default, absent query keys return null; using .withDefault provides a fallback value. Dependencies include 'nuqs-svelte'. Inputs depend on URL query presence; outputs are state values or defaults. Setting state to null removes the query key and reverts to the default. ```svelte
count: {count.current}
``` ```ts ``` -------------------------------- ### Configure History Mode for Query State Updates in Nuqs-Svelte (TypeScript) Source: https://github.com/rtrampox/nuqs-svelte/blob/main/README.md Allows configuring history behavior for state updates, either replacing the current history entry or pushing new ones for each change, enabling back button navigation. Uses 'nuqs-svelte' library. Inputs are state change calls; outputs update browser history mode. Can override the default per update call. ```ts // Default: replace current history with new state useQueryState("foo", { history: "replace" }); // Append state changes to history: useQueryState("foo", { history: "push" }); ``` ```ts const query = useQueryState("q", { history: "push" }); // This overrides the hook declaration setting: query.set(null, { history: "replace" }); ```