N
Nuxt8mo ago
Thr0nSK

Memory management in Nuxt

Hi there! I was wondering whether you could share some resources about memory management in Nuxt, specifically some anti-patterns and/or good practices. I've been having problems with huge memory leaks in my apps, and I don't know where to start looking for potential problems. The documentation is quite lacking in this regard, in my opinion. The only thing mentioning memory leaks that I was able to find was not to use ref outside the script setup context. I'd be happy to write the docs for this topic once I understand it in more detail.
4 Replies
Sam  K
Sam K8mo ago
@Thr0nSK nuxt on the frontend is basically vue so the same practices apply. On the top of my head you can destroy what's uneeded on onUnMounted hook, like event listeners, connections, heavy tasks, flush watchers etc... https://vuejs.org/guide/essentials/watchers.html#stopping-a-watcher in vue docs search for memory leaks there's a couple of pages.
Vue.js
Vue.js - The Progressive JavaScript Framework
Thr0nSK
Thr0nSKOP8mo ago
Thanks, but I am more concerned about the server part, though. For example, is a new nuxtApp created for every request or is it shared? I registrr a few nuxt hook callbacks in plugins on the server and they are only unhooked on the client - could that cause problems?
Sam  K
Sam K8mo ago
On the server side Nuxt does an excellent job at handling this stuff as people can get a bit careless. take as an example, recently the Nuxt team introduces useRequestEvent() that can run inside .vue components, if you do this
<script lang="ts" setup>
const event = useRequestEvent()

if (process.server) console.log(event)

if (process.client) console.log(event) // will be undefined
</script>
<script lang="ts" setup>
const event = useRequestEvent()

if (process.server) console.log(event)

if (process.client) console.log(event) // will be undefined
</script>
In terms of requests the defineEventHandler i believe it respects the session and request data so private data it's not leaked unless us the developers return data from the server that it should not be exposed. For hooks I used them in modules and plugins and they respect where they should run. Please I am intrested in this topic as well as I am building a lot fo ssr latley, so please if you find something intresting let us know 🙂
Thr0nSK
Thr0nSKOP7mo ago
I sure will. As I said, I'm planning to write a docs section about it when I gather more information. One thing I am curious about - the documentation mentions:
Never define const state = ref() outside of <script setup> or setup() function. Such state will be shared across all users visiting your website and can lead to memory leaks!
Do you think that it is safe to use ref and computed inside classes, if I only use the classes in script setup? Another question would be - is it ok to use them in the setup function of runtime plugins?
Want results from more Discord servers?
Add your server