Nuxt Tip: Run Code Once During SSR or CSR
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:
Warning
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. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: How I Write Class & Style Bindings
Styling your components in Vue.js can be done in multiple ways. One of the most common ways is to use the class attribute, especially if you are using a CSS framework like Tailwind. In combination with v-bind you can dynamically assign classes to your components.
Nuxt Tip: Change Status Code of the Response
`setResponseStatus` is a Nuxt composable to set the status code and (and optionally the status message) of the response.