In a Sapper application, I find myself frequently needing information about the current URL. For example, if you need to do any in-page skip linking (eg <a href="#top">Back to top</a>
), you need the current page path because Sapper inserts a <base href="/">
element in the head (an annoyance fixed in SvelteKit). So if you’re on a URL like /blog
, that really needs to be <a href="/blog#top">Back to top</a>
to avoid sending you back to the home page.
Client-side, you can access the path on location.pathname
or window.location.pathname
, but those aren’t available server-side, and requires some extra code to look it up in an onMount
function.
An alternative is that the @sapper/app
module exports a store with that information. It updates automatically and works both client and server-side:
<script>
import { stores } from '@sapper/app'
const { page } = stores()
</script>
<a href={$page.path + '#top'}>Back to top</a>
If you need to access it in scripts, you can do so in a reactive block:
<script>
import { stores } from '@sapper/app'
const { page } = stores()
$: {
console.log($page)
}
</script>
The $page
store has these properties:
host
path
query
: an object of any query/search keys and valuesparams
: an object of any active sapper route parameters
That’s it!