How to use callOnce in Nuxt

If you need to run a piece of code only once, there’s a Nuxt composable for that (since 3.9):

<script setup>
await callOnce(async () => {
// This will only be run one time, even with SSR
});
</script>

Using callOnce ensures that your code is only executed one time — either on the server during SSR or on the client when the user navigates to a new page.

It also has a key similar to useFetch or useAsyncData, to make sure that it can keep track of what’s been executed and what hasn’t:

<script setup>
['one', 'two', 'three'].forEach(item => {
// Run once for each item
callOnce(item, async () => {
// Do something with the item
});
});
</script>

By default Nuxt will use the file and line number to automatically generate a unique key, but this won’t work in all cases.