sveltekit-search-params

repository·master·Indexed 20 days ago

https://github.com/paoloricciuti/sveltekit-search-params

A library for SvelteKit that provides a reactive way to read and write URL query search parameters as if they were standard Svelte state. It includes the queryParameters() function for managing multiple parameters, the queryParam() function for single parameters, and ssp helpers for encoding and decoding complex types such as numbers, booleans, arrays, and objects.

Tokens
6.3K
Snippets
26
Records
26
Agent score
70%

What's inside sveltekit-search-params

  1. Develop and run the Svelte development server

    master

    After creating your project and installing dependencies (using npm install, pnpm install, or yarn), start the development server using npm run dev. You can use the --open flag to automatically open the app in a new browser tab.

    npm run dev
    
    # or start the server and open the app in a new browser tab
    npm run dev -- --open
  2. Configure store options for queryParam and queryParameters

    master

    You can pass a configuration object to customize the behavior of your search parameter stores.

    Note on placement:

    • For queryParam, pass the config as the third argument.
    • For queryParameters, pass the config as the second argument.

    Available Options:

    • debounceHistory (number): Milliseconds to delay writing to history. Useful for text inputs to avoid a history entry for every keystroke. Defaults to 0.
    • pushHistory (boolean): If false, the URL updates but no new entries are added to the browser history stack (user cannot use 'Back').
    • sort (boolean): Whether to sort search parameters in the URL for better cache-ability. Defaults to true. This is per-store.
    • showDefaults (boolean): If true (default), the library redirects to the URL containing the default value immediately on load. If false, the store holds the default value but the URL remains clean.
    • equalityFn (function): A custom function (current, next) => boolean to prevent unnecessary reactivity for complex objects/arrays. It is not used for primitive values. By default, it uses JSON.stringify.
    <script lang="ts">
    	import { ssp, queryParameters, queryParam } from 'sveltekit-search-params';
    
    	// Using queryParam with config (3rd argument)
    	const name = queryParam('name', ssp.string(), {
    		debounceHistory: 500,
    	});
    
    	const count = queryParam('count', ssp.number(), {
    		debounceHistory: 1500,
    	});
    
    	// Using queryParameters with config (2nd argument)
    	const store = queryParameters(
    		{
    			username: true,
    			isCool: ssp.boolean(true),
    		},
    		{
    			pushHistory: false,
    		},
    	);
    </script>
  3. Configure queryParameters options

    master

    The queryParameters function accepts a configuration object as its second argument to control how URL updates interact with the browser history and how default values are displayed.

    Options

    • debounceHistory (number): The delay in milliseconds before writing to history. Useful for text inputs to prevent every keystroke from creating a new history entry. Defaults to 0.
    • pushHistory (boolean): If false, the URL updates but no new entries are added to the browser's history stack (the user cannot use the 'Back' button to undo the change).
    • sort (boolean | false): By default, search parameters are sorted to improve cache-ability. Set to false to disable sorting. Note that this setting is per-object; interacting with a non-sorting object and then a sorting object will still result in a sorted URL.
    • showDefaults (boolean): If true (default), the library immediately navigates to the URL containing default values if they are missing. If false, the parameter will hold the default value in state, but the URL will not be updated to show it.
    <script lang="ts">
    	import { ssp, queryParameters } from 'sveltekit-search-params';
    	const params = queryParameters(
    		{
    			username: true,
    			isCool: ssp.boolean(true),
    		},
    		{
    			debounceHistory: 500, // url will change after 500ms
    			pushHistory: false, // no new history entries for this object
    		},
    	);
    </script>
  4. Fix Vite dependency errors with the ssp plugin

    master

    If you encounter issues with Vite, you may need to include the sveltekit-search-params/plugin in your vite.config.ts or vite.config.js. This is required if you are running on an older version of Vite or SvelteKit.

    import { sveltekit } from '@sveltejs/kit/vite';
    import { ssp } from 'sveltekit-search-params/plugin';
    
    /** @type {import('vite').UserConfig} */
    const config = {
    	plugins: [ssp(), sveltekit()],
    };
    
    export default config;
  5. Write to a single queryParam store (v3.0.0)

    master

    Because queryParam returns a Svelte store, you can use two-way binding (bind:value) or manual assignments to update both the local state and the URL simultaneously.

    <script lang="ts">
    	import { queryParam } from 'sveltekit-search-params';
    	const username = queryParam('username');
    </script>
    
    <input bind:value={$username} />
  6. Use `ssp` helpers for encoding and decoding

    master

    The ssp object provides shorthand helpers to avoid writing manual encode and decode functions for common types. These helpers can also accept an optional default value.

    Available helpers in ssp:

    • ssp.object(): Maps a JSON-serialized string to an object.
    • ssp.array(): Maps a JSON-serialized string to an array.
    • ssp.number(defaultValue?): Maps a string to a number.
    • ssp.boolean(): Maps 'true'/'false' strings to booleans.
    • ssp.string(): Explicitly treats the parameter as a string (for readability).
    • ssp.lz(): Maps a JSON-serializable state to its lz-string representation (useful for obscuring state in the URL).

    Example

    <script lang="ts">
    	import { ssp, queryParameters } from 'sveltekit-search-params';
    
    	const params = queryParameters({
    		username: true,
    		isCool: ssp.boolean(),
    		count: ssp.number(10),
    	});
    </script>
    <script lang="ts">
    	import { ssp, queryParameters } from 'sveltekit-search-params';
    
    	const params = queryParameters({
    		username: true,
    		isCool: ssp.boolean(),
    	});
    </script>
  7. Read and write query parameters with queryParameters()

    master

    The queryParameters function is the primary way to interact with search parameters.

    • Reading: Calling queryParameters() without arguments returns an object containing all current search parameters as strings.
    • Writing: The returned object is reactive. Updating a property on this object (e.g., params.username = 'new_value') will automatically update the URL.

    Example: Basic usage and writing to the store

    <script lang="ts">
    	import { queryParameters } from 'sveltekit-search-params';
    
    	const params = queryParameters();
    </script>
    
    <input
    	value={params.username}
    	oninput={(e) => {
    		params.username = e.target.value;
    	}}
    />
    <script lang="ts">
    	import { queryParameters } from 'sveltekit-search-params';
    
    	const params = queryParameters();
    </script>
    
    <pre>
        {JSON.stringify(params, null, 2)}
    </pre>
    <input
    	value={params.username}
    	oninput={(e) => {
    		params.username = e.target.value;
    	}}
    />
  8. Define expected parameters and default values

    master

    You can pass a configuration object to queryParameters to define which parameters you expect. This ensures they are present in the returned object even if they are missing from the URL.

    • Expected parameters: Pass a key with the value true to include it in the object (it will be null if not in the URL).
    • Default values: Use the defaultValue property within a parameter's configuration object to provide a fallback. When a default value is used, the URL will be updated to include this parameter once the client-side bundle loads.

    Warning: Because goto cannot run on the server, if the page is server-side rendered, the object will show the default value, but the actual URL navigation will only occur once the client-side code executes.

    Example

    <script lang="ts">
    	import { queryParameters } from 'sveltekit-search-params';
    
    	const params = queryParameters({
    		username: true,
    		count: {
    			encode: (value: number) => value.toString(),
    			decode: (value: string | null) => (value ? parseInt(value) : null),
    			defaultValue: 10,
    		},
    	});
    </script>
  9. Use queryParameters for multiple parameters (v3.0.0)

    master

    The queryParameters function returns a store containing an object of all present search parameters.

    Expected Parameters

    You can define a schema of expected parameters. These will be merged into the resulting object even if they are not present in the current URL. If a parameter is missing, its value will be null (or its defaultValue if specified).

    Encoding/Decoding in queryParameters

    Just like queryParam, you can specify custom encoding/decoding or use ssp helpers for individual keys within the schema object.

    <script lang="ts">
    	import { ssp, queryParameters } from 'sveltekit-search-params';
    
    	const store = queryParameters({
    		username: true,
    		isCool: ssp.boolean(true),
    	});
    </script>
    
    <pre>{JSON.stringify($store, null, 2)}</pre>