kit icon indicating copy to clipboard operation
kit copied to clipboard

Reactive writable URL Search Params with Svelte 5 runes

Open mquandalle opened this issue 1 year ago • 16 comments

Describe the problem

Storing state in the URL is a common practice and a recommended approach for state management in SvelteKit. Adding a way to easily change the search parameters of the current URL was previously discussed in issue #969, but this discussion predates the introduction of Svelte 5 runes.

With runes, keeping $state variables reliably synchronized with URL search parameters is challenging. page.url.searchParams can be used to read search params state, but not to write it, so we have to ressort on a sophisticated logic with $effect, snapshot, etc.

While community packages like sveltekit-search-params exist to address this pattern, the most popular one is not yet based on runes (see paoloricciuti/sveltekit-search-params#80 and relies on the deprecated $page store. I don't know any popular library that solve this issue the latest rune based APIs

I think SvelteKit should provided a built-in, rune-native, and documented way o manage this synchronization.

Describe the proposed solution

Integrate something like https://gist.github.com/PuruVJ/ed0abefbf512ff2aaa5dbbd377c50f5a by @PuruVJ into the framework.

Alternatives considered

No new api, but a new documentation page about how to read-write state in the URL.

Importance

nice to have

Additional Information

No response

mquandalle avatar Apr 27 '25 17:04 mquandalle

To add to this. If i do this:

page.url.searchParams.set("for", "customer")

This does not trigger a reaction when using:

  let active_href = $derived(page.url.search)

  // or
  
  $effect(()=> {
    console.log(page.url.searchParams.get("for"))
    console.log(page.url)
  })

gregg-cbs avatar Apr 30 '25 10:04 gregg-cbs

Also in the page.server.ts i am noticing issues, if I set the searchParams they do not end up on the url:

export function load({url}) {
  let who_for = url.searchParams.get("for") || ""

  if (!who_for) {
    who_for = "organiser"
    url.searchParams.set("for", "organiser")
    url.searchParams.append("for", "organiser")
    console.log(url.href); // http://localhost:5173
    // ^^ the search params are not on the href at this point

    console.log(url.searchParams.get("for")); // organiser
    // ^^ but getting from the params returns the set param
  }

  return {
    who_for
  }
}

Butt if I create a new URL from the existing, it works fine:

export function load({url: svelteUrl}) {
  let who_for = svelteUrl.searchParams.get("for") || ""

  if (!who_for) {
    who_for = "organiser"

    const url = new URL(svelteUrl.href)
    url.searchParams.set("for", "organiser")

    console.log(url.href); // http://localhost:5173?for=organiser
  }

  return {
    who_for
  }
}

gregg-cbs avatar Apr 30 '25 10:04 gregg-cbs

There is this https://svelte.dev/docs/svelte/svelte-reactivity#SvelteURL and also SvelteURLSearchParams - I haven't used it, but from the docs it looks like it's the reactive version you are looking for (?)

wiesson avatar Apr 30 '25 12:04 wiesson

Yes, but it isn't synced with the page URL on SvelteKit.

mquandalle avatar Apr 30 '25 12:04 mquandalle

At least for my case, using goto to set URL search parameters solved this issue for me and causes page.url.searchParams to be reactive.

Previously I was using pushState or replaceState which didn't seem to allow reactivity on page.url.searchParams.

<script>
    import { goto } from "$app/navigation";
    import { page } from "$app/state";

    let foo = $state('');
    let searchParams = $derived(page.url.searchParams);

    $effect(() => {
        if (searchParams.get('foo') === 'bar') {
            console.log('foo is bar');
        }
    })
</script>


<form>
    <input
        type="text"
        bind:value={foo}
    />

    <button
        onclick={(e) => {
            e.preventDefault();
            goto(
                `?foo=${foo}`, 
                {
                    replaceState: false,
                    keepFocus: true,
                    noScroll: true,
                }
            );
        }}
    >
        Set Search Params
    </button>
</form>

<div>
    {searchParams}
</div>

mkmoisen avatar May 03 '25 17:05 mkmoisen

Same, doing all types of wild dances to sync searchParams

goto has lag on url update if some data is loading pushState shows incorrect values when using back/forward buttons (possible bug in sveltekit)

Internal functionality for url sync would make life much easier 🙌

vladshcherbin avatar Jun 19 '25 11:06 vladshcherbin

<script lang="ts">
import { page } from '$app/state';
let searchParams = $derived(page.url.searchParams);
let currentTab = $derived(searchParams.get('tab') || 'service');

$inspect("Currrent Tab", currentTab)
</script>

this seems to work for me, the log prints Current Tab with the current value whenever the URL param changes

sivasiva avatar Jun 19 '25 18:06 sivasiva

If you get here because you are trying to manipulate URL query strings via navigation and page does not show your changes, it is possible that you are mutating page.url.searchParams directly and getting all kind of strange behaviors.

If you are trying to build a new URL with the existing query strings.

You should do the following:

// this
const params = new URLSearchParams(page.url.searchParams.toString())
// not the following since it'd mutate `page` directly
// const params = page.url.searchParams;
params.set('my-new-param', 'toto');

http-teapot avatar Jul 31 '25 00:07 http-teapot

If you get here because you are trying to manipulate URL query strings via navigation and page does not show your changes, it is possible that you are mutating page.url.searchParams directly and getting all kind of strange behaviors.

Oof. Svelte 5 kind of messed up all my expectations about how things work. Everything used to be so intuitive, and now I need to search GitHub issues to learn how to have a reactive query parameter—and there isn't even a definitive answer here…

Radiergummi avatar Oct 13 '25 09:10 Radiergummi

There is useSearchParams from runed. The code is indeed quite complex https://github.com/svecosystem/runed/blob/main/packages/runed/src/lib/utilities/use-search-params/use-search-params.svelte.ts

mquandalle avatar Oct 13 '25 10:10 mquandalle

Once we can reliably know it's a Svelte 5 project we should be able to make page.url an instance of https://svelte.dev/docs/svelte/svelte-reactivity#SvelteURL which means everything will be reactive as expected

Update: I may have misread the original request - it will be reactive in the sense that it will be fine-grained as expected, but the writeable part will not be solved with this

dummdidumm avatar Oct 13 '25 10:10 dummdidumm

@dummdidumm is there any progress or suggested workaround for this?

Simple example:

<script lang="ts">
  import { goto } from '$app/navigation'
  import { resolve } from '$app/paths'
  import { page } from '$app/state'
  import { getCars } from '$lib/remote/get-cars.remote.ts'

  let price = $derived(Number(page.url.searchParams.get('price') ?? '0'))
  const carsCount = $derived(await getCars(price))

  async function handleChange() {
    const url = new URL(page.url)

    url.searchParams.set('price', String(price))

    await goto(resolve(`/?${url.searchParams.toString()}`), { keepFocus: true })
  }
</script>

<input type="number" bind:value={price} onchange={handleChange} />

<p>price - {price}</p>
<p>cars - {carsCount}</p>

Changing input value quickly gives all kind of warnings e.g.:

[svelte] await_waterfall An async derived, carsCount (src/​routes/​+page.svelte:8:20) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app https://svelte.dev/e/await_waterfall

vladshcherbin avatar Apr 02 '26 19:04 vladshcherbin

I worked through this rather quickly, and it might be a work in progress, but I just know I'm on to something. Of course, open to feedback.

I'd like to take a stab at the SvelteURL direction suggested above, targeting version-3.

A little archaeology first, because I wondered why page.url wasn't reactive from day one. Turns out it couldn't be. kit 2.x supports svelte: ^4 || ^5, and state.svelte.js loads unconditionally in the client runtime, so importing svelte/reactivity there would crash every Svelte 4 app, the module doesn't exist for them. version-3 raises the floor to svelte: ^5.48.0, so the blocker dissolves exactly on the branch a breaking change wants to land on anyway. Convenient.

The change itself is small. The runes branch of state.svelte.js already models page as a class with $state.raw fields, and url becomes a stable SvelteURL behind a getter/setter:

page = new (class Page {
	// ...
	#url = new SvelteURL(placeholder_url);
	get url() {
		return this.#url;
	}
	set url(value) {
		this.#url.href = value.href;
	}
})();

Both router assignment sites in client.js keep working untouched, they assign plain URLs and the setter funnels them into an href write. SvelteURL only notifies the per-property signals whose value actually changed, so:

$effect(() => page.url.pathname); // no longer wakes up when only ?q= changes
$effect(() => page.url.search);   // no longer wakes up when only the pathname changes
$effect(() => page.url);          // never fires again. this is the breaking change

That third line is why this is v3 material and not a 2.x patch. Today url is $state.raw and replaced wholesale per navigation, so identity-based effects fire on every navigation. With in-place mutation they silently stop. Needs a migration note.

Two honest limitations from reading the svelte side. searchParams reads don't get the fine-grained treatment yet, because SvelteURL's href setter unconditionally replaces the params and bumps their single version signal even when nothing changed (sveltejs/svelte#17218 is a symptom of this). Fixable upstream with a diff check in the replace path, and I'm happy to send that PR to svelte as a companion. Meanwhile kit's own internals look ready, the one hot-path read of page.url outside the router is already wrapped in untrack with a comment anticipating exactly this, though I'd audit the rest in the PR.

Questions where I'd want direction before touching the writable half (the actual ask in this issue):

  1. Should page.url.searchParams.set(...) navigate, and if so with replaceState or pushState semantics by default?
  2. Batch multiple synchronous mutations into one history entry, presumably via a microtask?
  3. Should load functions re-run, or is this shallow-routing territory?
  4. Should the reads-only first step ship with a DEV warning on external mutation? Today mutating page.url.searchParams silently desyncs the router because current.url, page.url and the $app/stores page share one instance (several comments above are hitting exactly this). With reactive reads but no navigation, that footgun gets quieter, not louder.

Happy to open the reads-only PR against version-3 first if this direction still sounds right.

Nic-Polumeyv avatar Jun 12 '26 13:06 Nic-Polumeyv

Related: #12870 which proposes the opposite for the "writeable" part - making the URL immutable.

dummdidumm avatar Jun 26 '26 11:06 dummdidumm

I lean more towards #12870 personally. If you're manipulating the URL you should have to be explicit about whether you're creating a new history entry or not. The mechanism for doing so is goto

Rich-Harris avatar Jun 26 '26 13:06 Rich-Harris

We just discussed this in the maintainers meeting and agreed that we don't want to make page.url.searchParams writeable. While it would allow you to change the URL a bit more ergonomically, it's not that more ergonomic that it justifies the added potential confusion about how you can change the URL in SvelteKit.

Furthermore, it would probably only get you half-way where you actually want to be. An ideal solution would be both ergonomic (manipulating page.url.searchParams would only be slightly more ergonomic than using goto today) and type-safe. We will revisit this at some point but not now.

In the meantime, https://github.com/paoloricciuti/sveltekit-search-params is now using Svelte 5 and provides a nice API for this use case.

dummdidumm avatar Jun 26 '26 16:06 dummdidumm