The plugin is executed twice
Hello.
I have the plugin (), which generates (or refreshes) a token. But it is executed twice: on the server and on the client. But I need the plugin start only once. If it was executed on the server, it should not be executed on the client.
But also I use SPA of this project for mobile app (Capacitor) and I can't to rename plugin to because in this case the plugin have to start on the client.
What are the appropriate options to solve my problem?
2 Replies
Hi @Yuri. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To address your issue with the plugin being executed twice (on both server and client) while maintaining compatibility with SPA/mobile app usage, you can use the
callOnce
utility in Nuxt 3.9 and later. This utility is designed to execute a given function only once during server-side rendering or client-side navigation.
Here's how you can modify your plugin to achieve the desired behavior:
This approach offers several advantages:
1. The code inside callOnce
will only be executed once, either on the server or the client, but not both.
2. You don't need to rename your plugin to 01.init.server.ts
, maintaining compatibility with SPA/mobile app usage.
3. It works for both server-side rendering and client-side navigation scenarios.
The callOnce
utility is specifically designed to handle this kind of situation, where you want to ensure that certain code runs only once, regardless of whether it's on the server or client.
Source: Nuxt Documentation - callOnce
Keep in mind that if you're using Nuxt version earlier than 3.9, you might need to update your Nuxt version to use this feature. If updating is not an option, you may need to implement a custom solution using flags or other mechanisms to prevent double execution.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@740173469404364872> Kapa.ai is still learning and improving, please let me know how I did by reacting below.