DEV Community

Cover image for Grab Current URL in Svelte (2023)
Michael Amachree
Michael Amachree

Posted on • Edited on

Grab Current URL in Svelte (2023)

Not long ago, I was working on creating an app, and I had this puzzle to solve: How do I figure out the current page's path and apply a CSS style to show it's active? It got a bit tricky because I was using Svelte Kit, and I needed those routes to be super responsive. Sure, I could've gone with regular JavaScript, but that felt a bit too wordy and not as snappy as I wanted it to be. Here's what I mean:


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

  let current_url = '';

    onMount(() => current_url = window.location.href);
</script>
  <p>{current_url}</p>


Enter fullscreen mode Exit fullscreen mode

But, you know, this wasn't exactly what I had in mind. So, I went on a little quest to find the solution I was after. And, well, since I couldn't seem to locate this solution anywhere else, I thought, why not share it right here? You never know, it might come in handy for someone else down the road. 😊



<script>
    import { page } from '$app/stores';
 let current_url = $page.url.pathname.split('/').filter(Boolean).pop() || '/';
</script> 

  <p>{current_url}</p>


Enter fullscreen mode Exit fullscreen mode

This here might come in handy for those who are looking to grab that '/' path. Now, if that's not quite your thing, no worries, you can just breeze right past that '||' part in the code. It's all about making things work just the way you need them to! 😄

Now, let's get into it. It wouldn't be great if I left you hanging, right? You see, the code does its thing, and the 'current_url' is spot on as the current page. But, there's a little catch - it doesn't quite update when you hop from page to page. It only does its magic when you hit that refresh button. And here's where the fun begins - to make it all tick as it should, we've got a little trick up our sleeve (you could call it a hack, if you like). 😄



<script>
 import { page } from '$app/stores';
import { afterUpdate } from 'svelte';
// Set the current URL
let current_url = $page.url.pathname.split('/').filter(Boolean).pop() || '/';

// Set it as soon as pages update
afterUpdate(() => {
  current_url = $page.url.pathname.split('/').filter(Boolean).pop() || '/';
});
</script>

<p>{current_url}</p>


Enter fullscreen mode Exit fullscreen mode

Now then, everything should be running smoothly, with no hiccups in sight. 😄

I really hope this comes in handy for you, especially if you were looking for something like this. For an updated version with even more information, check out my new article here:

Happy URL Snatching!

Top comments (1)

Collapse
 
sindbad_x profile image
Sindbad_X

You can make it more concise by doing this:


  let currentPath = "/"
  $: currentPath = $page.url.pathname.split('/').filter(Boolean).pop() || '/'

Enter fullscreen mode Exit fullscreen mode