Table of Contents
Get this article emailed to you .
SvelteKit version: 1.0.0
With SvelteKit, there a few utilities (mostly from native web APIs/functions) that are provided out of the box, and that allow dealing easily with query parameters on the client and on the server.
In this article, we will go through a few examples of how to use query parameters in SvelteKit.
What are query parameters?
Query parameters are a part of a URL that comes after a question mark
and are separated by an ampersand
. They can be used both for storing data and performing actions on the client, but also for passing data to the server.
For example, in the URL
, the query parameters are
, and their values are
Client-side query parameters with SvelteKit
In SvelteKit, on the client, most of the properties related to the current page and the URLs are available in the
store from the
This will output the following:
You will notice the
property, which is just the native URL.searchParams property. This property can help retrieve the query parameters that are present in the current URL.
For instance, when I visit the following URL:
, I can access the query parameters with the following code:
Now you can use the parameters and perform any actions you want on the client.
One example of something I’ve done lately was on EasyRegex. When someone generates a Regex, there’s a button that takes them to the validation page with the generated Regex already in the input. Validations URLs look like this:
Using query parameters on the server
SvelteKit can be considered a full-stack web framework
. Because of that, every rendered page has a corresponding request with the same
property as the one we saw earlier.
This means that we can access the query parameters on the server as well as load functions and form actions.
Here is an example of how to access query parameters in a load function:
property can be directly destructured from the load function parameters. It is also available on the
parameter of the
function. So, we could also write the following:
Having access to the query parameters on the server load function is very useful. For example, you can use them to fetch data from an API and return it to the client in case the URL contains a necessary parameter.
If you are using SvelteKit daily, it is useful to know that the framework takes a lot of advantage of many native browser APIs. This is the case with the URL interface, but also to a lot of other APIs.
Read the official SvelteKit documentation about web standards.
Get help with your Svelte or SvelteKit code
Got a Svelte/Sveltekit bug giving you headaches? I’ve been there!
Book a free 15 min consultation call, and I’ll review your code base and give you personalized feedback on your code.
P.S. If you have a bigger problem that may need more than 15 minutes, you can also pick my brain for a small fee. 😊 But that’s up to you!