DEV Community

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

Posted on • Edited on

4

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:

<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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay