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:
import { defineNuxtPlugin, callOnce } from '#app'
export default defineNuxtPlugin((nuxtApp) => {
callOnce(async () => {
console.log('Generating or refreshing token')
})
})
This approach offers several advantages:
- The code inside
callOnce will only be executed once, either on the server or the client, but not both.
- You don't need to rename your plugin to
01.init.server.ts, maintaining compatibility with SPA/mobile app usage.
- 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: