š Type-Safe Query Parameter for SvelteKit
npm i svelte-qparam
Use the define
function to set multiple parameter definitions at once.
<script>
import { page } from '$app/state'
import { define } from 'svelte-qparam'
import { string, number, boolean } from 'svelte-qparam/serde'
const extract = define({
str: string,
num: number,
bool: boolean
})
// https://example.com/?str=value&num=123&bool=false
let { values, qparams: q } = $derived(extract(page.url))
// {
// str: 'value',
// num: 123,
// bool: false
// }
console.log(values)
// output 'value'
console.log(q.str)
q.num = 456
q.bool = true
</script>
Values defined with the define
function can be used in +page.js
and +page.server.js
.
This allows you to handle parameters type-safely across applications across servers and clients.
// +page.js
import { define } from 'svelte-qparam'
import { string, number, boolean } from 'svelte-qparam/serde'
export const _extract = define({
str: string,
num: number,
bool: boolean
})
export const load = ({ url, data }) => {
const { values, qparams } = _extract(url)
// ...
return {
qparams
}
}
// +page.server.js
import { _extract } from './+page.js'
export const load = ({ url }) => {
const { values } = _extract(url)
// ...
return {
// Note: Cannot return `qparams` from server
// ...
}
}
<!-- +page.svelte -->
<script>
let { data } = $props()
let { qparams: q } = $derived(data)
// ...
</script>