[SveletKit FAQs] Routes Frequently Asked Questions (FAQs)

Routes FAQs

Get current URL

Via SveletKit stores

page is a readable store whose value reflects the object passed to load functions — it contains host, path, params and query. See the page section page | Docs • SvelteKit - https://kit.svelte.dev/docs#loading-input-page above for more details.

See $app/stores | Docs • SvelteKit - https://kit.svelte.dev/docs#modules-$app-stores to learn more.

1
2
3
4
5
6
7
<script>
import { page } from '$app/stores';

console.log($page.path)
</script>

<p>Current URL: {$page.path}</p>

Suppose the current URL is https://example.com/page/, in the above example.

In that case, $page.path will return /page/.

Via window.location.href

If you want the full URL, you can prepend window.location.origin (once the component has mounted).

1
2
3
4
5
6
7
8
9
<script>
import { onMount } from 'svelte';

let url = ``;

onMount(async () => url = window.location.href);
</script>

<p>Current URL: {url}</p>

In the above example, the URL is not reactive, but it will return the complete URL rather than just the current page.

So if the current URL is https://example.com/page/, url will return https://example.com/page/, because it is simply grabbing window.location.href, a vanilla JavaScript string.

See Get Current URL in Svelte - https://natclark.com/tutorials/svelte-get-current-url/ to learn more.

References

[1] $app/stores | Docs • SvelteKit - https://kit.svelte.dev/docs#modules-$app-stores

[2] page | Docs • SvelteKit - https://kit.svelte.dev/docs#loading-input-page

[3] SvelteKit • The fastest way to build Svelte apps - https://kit.svelte.dev/

[4] Svelte • Cybernetically enhanced web apps - https://svelte.dev/