Retrieving query string parameters in SvelteKit is a relatively straightforward process, primarily involving the use of the page object within the page's load function. The page object contains information about the request, including the URL and query string parameters. Below are the steps and examples for retrieving query string parameters:
Step 1: Create a SvelteKit project
If you don't already have a SvelteKit project, you can quickly set up a new one:
bashnpm init svelte@next
Step 2: Define the page component
Create a new Svelte file in the src/routes directory, for example, src/routes/example.svelte.
Step 3: Use the load function to retrieve query string parameters
Within your page component, define a load function to extract query string parameters. This function receives a parameter containing a page property, where the url property of the page object holds information about the current page's URL.
svelte<script context="module"> export async function load({ page }) { const urlParams = page.url.searchParams; // Retrieve a specific query parameter const param = urlParams.get('param'); // assuming the URL is ?param=value return { props: { param // Pass the parameter to the component's props } }; } </script> <script> export let param; </script> <main> <h1>The value of the query parameter is: {param}</h1> </main>
Example Explanation
In the above example, we define a load function that uses page.url.searchParams to access the URL's query parameters. searchParams is a URLSearchParams object providing utility methods for handling query strings.
We obtain the specific query parameter value by calling the get method with the parameter name (param), then pass this value as a prop to the page component.
Testing
You can test this functionality by accessing the following URL in your browser:
shellhttp://localhost:3000/example?param=value
This should display "The value of the query parameter is: value" on the page.
By using this approach, you can flexibly retrieve and utilize URL query string parameters to dynamically adjust page content or behavior based on user needs.