·
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
<script setup lang="ts"> if (process.client) { console.log('Client href', window.location.href) } </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
<script setup lang="ts"> const url = useRequestURL() </script> <template> <p>URL is: {{ url }}</p> <p>Path is: {{ url.pathname }}</p> </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.