Skip to site navigation
Go home

Lee Reamsnyder

How to get the current URL in a Sapper app

2021 Mar 18 2 min read Published by Lee Reamsnyder Permalink

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 values
  • params: an object of any active sapper route parameters

That’s it!

← Older post Donald Trump is bad and should feel bad → Newer post How to Favicon in 2021

Menu

  • Home
  • Blog
  • Work
  • Contact
  • Archives
  • Feeds: RSS | JSON

Search

Elsewhere

  • GitHub
  • Instagram
  • Mastodon
  • Twitter
© Copyright 2006–2023, Lee James Reamsnyder
Back to top