Nuxt Tip: An URL Object Working on Both Server-Side and Client-Side
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:
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:
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:
Vue Tip: Simple State Management With Composition API
Learn how you can use Composition API for a simple state management solution which you can use instead of Pinia.
Vue Tip: Deep Watch on Arrays
In Vue 3, when using the watch option to watch an array, the callback will only trigger when the array is replaced. To trigger the watcher on mutation, the deep option must be specified.