How can make my project's module composables be used my the server?
Hey Nuxt people!
I have a basic Shopify module that is working correctly for me:
But when I use my
useShopify composable in the /server folder, it doesn't seem to register.. For instance on my /server/api/sitemap.ts I can't seem to reach my useShopify composable:
Any help would be really appreciated!3 Replies
Hi @Rylan. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To make your module's composables (like
Nuxt separates the auto-imports for the Vue app and the Nitro server. Composables registered with
Add your composable with
useShopify) available for use inside the /server directory (e.g., in server routes or API handlers), you need to register them as server imports rather than just regular imports. The addImports utility only makes composables available for auto-import in the Vue app context (client and universal composables), but not in the server context (Nitro server handlers).
For server-side usage, you should use addServerImports (for individual files) or addServerImportsDir (for directories). This will allow Nitro to auto-import your composables in server files.
Here's how you can update your module:
Alternatively, if you have multiple composables, you can use addServerImportsDir to register a whole directory:
Why is this needed?Nuxt separates the auto-imports for the Vue app and the Nitro server. Composables registered with
addImports are not available in the server context by default. Using addServerImports or addServerImportsDir ensures your composables are available for auto-import in server files like /server/api/sitemap.ts see official docs.
References:
- Injecting Composables With addImports and addImportsDir
- addServerImportsDir API
Summary:Add your composable with
addServerImports or addServerImportsDir in your module's setup to make it available in the server context. This will resolve the issue and allow you to use useShopify() in your /server files.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@622945064233992224> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
^ Surprisingly AI was right this time