Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The easiest way to reactively manage query params in Svelte and SvelteKit applications, both on the server and in the browser.

License

NotificationsYou must be signed in to change notification settings

Ernxst/svelte-query-params

The easiest way to reactively manage query params in Svelteand SvelteKit applications, both on the server and in the browser. Built for Svelte 5 and integrates with existing validation libraries to parse, coerce and transform query params into the data your application needs.

Installation

svelte^5 is required:

npm install svelte-query-params svelte@next
pnpm install svelte-query-params svelte@next
yarn add svelte-query-params svelte@next
bun install svelte-query-params svelte@next

svelte requires a version of5.0.0-next.169 or newer as itrenamed a public API that this library uses.

By default,svelte-query-params usesURLSearchParams to handle interpreting the location string, which means it does not decodenull and has limited handling of other more advanced URL parameter configurations. If you want access to those features, add a third-party library like query-string and tellsvelte-query-params to use it.

Features

  • Reactivity: The library providies a reactive object that reflects the current state of query parameters.

  • Browser and Server Support: The utility is designed to work seamlessly in both browser and server environments.

  • Customizable Validators: Define validators for each query parameter to ensure proper data types and constraints.

  • Debounced Updates: Optionally debounce updates to query parameters to optimize performance.

  • Event Handling: Automatically handlespopstate events for accurate synchronisation with browser history.

  • Serialisation: Control how query params are serialised into strings to the browser

  • Multi-value params: Supports multi-value query parameters with ease

Usage

In some lib file e.g.,src/lib/params.ts:

import{createUseQueryParams}from"svelte-query-params";// Define validators for query parametersconstvalidators={page:(value)=>typeofvalue==="number"&&value>0,q:(value)=>typeofvalue==="string",};// Create the hookexportconstuseQueryParams=createUseQueryParams(validators);

createUseQueryParams returns a hook, rather than the reactive object itself, as the reactive nature may be lost when exporting and importing these files.

Then you can use this hook in your Svelte components:

<script>import {useQueryParams }from"$lib/params";// Import assuming SvelteKitimport {page }from"$app/stores";const [params,helpers]=useQueryParams($page.url);// You must pass the URL// Access query parametersconsole.log(params.page);// Current 'page' valueconsole.log(params.q);// Current 'q' value// Set query parametersparams.page=1;params.q="example";// Raw query params from the browser, all as stringshelpers.raw;// All query params, including those that were not set in schemahelpers.all;// Readonly search string, with the ? prefixhelpers.search;// Update all query parameters in bulkhelpers.update({ page:2, q:'shoes' });// Apply partial updates to query paramshelpers.update({ page:3 });// Remove query parametershelpers.remove("q");// Unsubscribe from popstate eventshelpers.unsubscribe();// Access query keyshelpers.keys();// Access entries:helpers.entries();</script><p>  Currently on page {params.page}, searching for {params.q}</p><!-- Bind the 'q' query param to the input --><inputname="search"bind:value={params.q}>

Validators

svelte-query-params supportszod,valibot and function validators to define the schema for query params. Therefore, you do not need to learn an extra API for validating data.

When usingzod orvalibot, you do not need to wrap your schemain zodz.object({ ... }) or valibotobject:

import{z}from"zod";import{createUseQueryParams}from"svelte-query-params";constuseQueryParams=createUseQueryParams({page:z.number(),q:z.string()});

But you can if you want.

Note that it is possible to mix and match the schemas if needed:

import{z}from"zod";import{string}from"valibot";import{createUseQueryParams}from"svelte-query-params";constuseQueryParams=createUseQueryParams({page:(value)=>typeofvalue==="number"&&value>0,sort:string(),q:z.string()});

Array Values

With a function validator, you may receive the param as either a string, an array of strings, or undefined. As a result, you must handle all three cases to support multi-value params:

constvalidators={categories:(value)=>{if(!value)return[]returnArray.isArray(value) ?value :[value]}}

With Zod, you need to handle the case where there's either 0 or 1 query param value as this library will not infer this as an array beforehand. You must define your array parameter like:

import{z}from"zod";z.object({categories:z.union([z.string().array(),z.string()]).default([]).transform((c)=>(Array.isArray(c) ?c :[c])),})

The union between a string and array of strings handles 1 or more query params; a default is set to the empty array to allow the parameter to be omitted from the URL and it's transformed at the end to convert the single value param into an array.

In the same manner, with Valibot:

import*asvfrom"valibot";v.object({categories:v.pipe(v.optional(v.union([v.array(v.string()),v.string()]),[]),v.transform((c)=>(Array.isArray(c) ?c :[c]))),});

Options

createUseQueryParams takes an options object as the second argument, with the following properties:

OptionDefaultDescription
windowObjwindow(Optional) Provide a custom implementation ofwindow. It must implement:Window.prototype.location,Window.prototype.history,EventTarget.prototype.addEventListener andEventTarget.prototype.removeEventListener.
debounce0(Optional) The delay in milliseconds before updating the browser URL when the reactive object is updated. This is useful in situations where URL updates happen frequently, e.g., on every keystroke. Note that this only affects the browser URL - the reactive object will always update immediately.
serialiseJSON.stringify(Optional) Control how query params are serialized to the URL. Note that this isNOT for encoding values into URI components - it serializes objects into strings, which will then be encoded internally. This is used for serialising complex objects like dates.
adapterbrowser(Optional) Provide a custom adapter that controls fetching/updating query params on both the server and in the browser.

Example

import{createUseQueryParams}from"svelte-query-params";constuseQueryParams=createUseQueryParams({ ...},{   ...// Options here})

Adapters

As mentioned previously, adapters control how the URL is fetched and updated, both on the server and in the browser. As such, any adapter needs to implement the following interface:

  • isBrowser: () => boolean - Returnstrue when are in the browser, andfalse otherwise.

  • server - A property with the following methods:

    • save(search: string) => void - Update the server URL. Note that thesearch string has the? prefixed.
  • browser - A property with the following methods:

    • read() => URL | Location - Retrieve the browser URL.
    • save(search: string, hash: string) => void - Update the browser URL. Note that thesearch string has the? prefixed and thehash string has the# prefixed.

To create your own adapter, you can import theAdapter type fromsvelte-query-params/adapter for intellisense, or usedefineAdapter also exported bysvelte-query-params/adapter:

importtype{Adapter}from'svelte-query-params/adapter';import{defineAdapter}from'svelte-query-params/adapter';exportconstmyAdapter:Adapter={ ...}exportconstmyAdapter=defineAdapter({ ...});

Browser

This is the default adapter when no adapter is specified and can only be usedin the browser i.e., fetching the URL on the browser returns an empty search string and hash and updating the query params on the server is a no-op.

import{createUseQueryParams}from"svelte-query-params";import{browser}from"svelte-query-params/adapters/browser";constuseQueryParams=createUseQueryParams({ ...},{adapter:browser({ ...})})

Browser Adapter Options

SvelteKit

For use with SvelteKit, use this adapter, instead of thebrowser adapter for support for interacting with query params on the server.

import{createUseQueryParams}from"svelte-query-params";import{sveltekit}from"svelte-query-params/adapters/sveltekit";constuseQueryParams=createUseQueryParams({ ...},{adapter:sveltekit({ ...})})

SvelteKit Adapter Options

  • replace: (Optional) If this istrue, any browser query updates will not create a new browser session history item, replacing the previous one instead. Iffalse, a new item will always be added to the history.

Contributing

SeeContributing Guide.

License

Distributed under the MIT License. SeeLICENSE for more information.

About

The easiest way to reactively manage query params in Svelte and SvelteKit applications, both on the server and in the browser.

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    [8]ページ先頭

    ©2009-2025 Movatter.jp