Javascript is required
·
1 min read

Nuxt Tip: An URL Object Working on Both Server-Side and Client-Side

Nuxt Tip: An URL Object Working on Both Server-Side and Client-Side Image

Sometimes you need access to the current URL object in your Nuxt application. For example, you might want to get the current path or query parameters.

If you are using SSR (Server Side Rendering) your code will be executed on the server and the client. This means that you need to make sure that your code works on both the server and the client. For example, you can't use the window object on the server.

A simple workaround is to add an if statement to check if the window object is available:

App.vue
1<script setup lang="ts">
2if (process.client) {
3  console.log('Client href', window.location.href)
4}
5</script>

This works but it's not very elegant. It would be better if we could use the same code on both the server and the client.

Luckily, Nuxt provides a helper function called useRequestURL that returns a URL object working on both the server side and client side:

App.vue
1<script setup lang="ts">
2const url = useRequestURL()
3</script>
4
5<template>
6  <p>URL is: {{ url }}</p>
7  <p>Path is: {{ url.pathname }}</p>
8</template>

Try it yourself in the following StackBlitz playground:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.