Vue & Nuxt Tips
·
1 min read
·
257 views

Nuxt Tip: Run Code Once During SSR or CSR

Michael Hoffmann

Michael Hoffmann

@mokkapps

Nuxt Tip: Run Code Once During SSR or CSR Image

Since Nuxt 3.9 you can use the useOnce composable to run a given function or block of code once during server-side rendering or client-side navigation.

This is useful if you want to run a function only once during the initial render of a page. For example, you might want to log a certain event or set up a global state that should only be initialized once.

Let's take a look at an example:

app.vue
<script setup lang="ts">
await callOnce(async () => {
  console.log('This will only be logged once')
})
</script>
Two things to note:
  • callOnce doesn't return anything, so you can't use it to return a value or promise.
  • You need to the callOnce composable in a setup function, plugin or route middleware because it needs to access the Nuxt payload.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more.