Taking advantage of query parameters in SvelteKit
Last updated on
Table of Contents
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 take 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 as a full-stack web framework. Because of that, every page that is rendered has a corresponding request, that has the same
property as the one we saw earlier. This means that we can access the query parameters on the server as well in 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 day-to-day, it is useful to know that the framework takes a lot of advantage of a lot of native browser APIs. This is the case of the URL interface, but also to a lot of other APIs.
Read the official SvelteKit documentation about web standards.