Get Current URL in Svelte

- 1 minute read

The method for grabbing the current URL in Svelte depends on whether you’re using Svelte or SvelteKit.

I’ll start with the SvelteKit example:

<script>
    import { page } from '$app/stores';
</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/.

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

Anyway, here is the non-SvelteKit (vanilla Svelte) example:

<script>
    import { onMount } from 'svelte';

    let url = ``;

    onMount(() => 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.

Link to this section Conclusion

Anyway, I hope you found this useful! Happy URL-grabbing.