N
Nuxt5d ago
dmarr

Module that uses fetch

I am working on making a module that will perform a fetch and update some runtime config. Using nuxt hub as an inspiration. I am running into an issue, likely because I’m trying to use a function that I define in server/utils. I don’t get any specific error, just that the module won’t load.
8 Replies
kapa.ai
kapa.ai5d ago
Hi @dmarr. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- I understand you're creating a Nuxt module that needs to perform a fetch operation and update runtime config, similar to Nuxt Hub. The issue you're facing with using a function from server/utils is likely related to how modules are loaded and executed in Nuxt. When developing Nuxt modules, there are some important best practices to follow: 1. Avoid CommonJS syntax: Nuxt 3 relies on native ESM, so make sure you're using ES modules syntax in your module code Nuxt Module Best Practices. 2. Be careful with async behavior: While modules can be asynchronous, Nuxt will wait for your module to set up before moving to the next module. If your module takes more than 1 second to set up, Nuxt will emit a warning Nuxt Module Best Practices. 3. Server utilities access: When creating a module, you need to be careful about how you access server-side utilities. The server directory is processed differently than module code. For fetching data in your module, you can use $fetch which is available globally in Nuxt:
// In your module
export default defineNuxtModule({
setup(options, nuxt) {
// Use $fetch to make HTTP requests
const fetchData = async () => {
try {
const data = await $fetch('<https://api.example.com/data'>)
// Update runtime config
nuxt.options.runtimeConfig.myModule = {
...nuxt.options.runtimeConfig.myModule,
fetchedData: data
}
} catch (error) {
console.error('Error fetching data:', error)
}
}

// Call the fetch function
fetchData()
}
})
// In your module
export default defineNuxtModule({
setup(options, nuxt) {
// Use $fetch to make HTTP requests
const fetchData = async () => {
try {
const data = await $fetch('<https://api.example.com/data'>)
// Update runtime config
nuxt.options.runtimeConfig.myModule = {
...nuxt.options.runtimeConfig.myModule,
fetchedData: data
}
} catch (error) {
console.error('Error fetching data:', error)
}
}

// Call the fetch function
fetchData()
}
})
If you need to use functions from your server/utils directory, consider: 1. Moving those utilities to a separate package that both your module and server can import 2. Creating the utilities directly in your module code 3. Using Nuxt hooks to run your server utilities at the appropriate time in the Nuxt lifecycle For runtime config updates, you can access and modify nuxt.options.runtimeConfig in your module's setup function as shown above. If you need more specific help, please share the code you're using in your module and the exact error you're encountering. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5d ago
<@139883350096740354> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
dmarr
dmarrOP5d ago
@kapa.ai how would I access runtime env in my module that is set from the envinronment? When I use the ready hook, the values I set with my .env file don't appear to be loaded yet.
kapa.ai
kapa.ai5d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I understand you're having trouble accessing environment variables in your Nuxt module, particularly when using the ready hook. This is a common issue with the timing of when environment variables are loaded in the Nuxt lifecycle. In Nuxt, environment variables from .env files are loaded during the initialization phase, but there's a specific way they need to be accessed in modules: 1. Environment variables in .env files are accessible via process.env during development and build time, but not directly as runtime config values until they're properly defined in your nuxt.config.ts file. 2. For runtime config values that come from environment variables, you need to explicitly define them in your nuxt.config.ts file with the NUXT_ prefix pattern:
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: process.env.NUXT_API_SECRET,
public: {
apiBase: process.env.NUXT_PUBLIC_API_BASE
}
}
})
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: process.env.NUXT_API_SECRET,
public: {
apiBase: process.env.NUXT_PUBLIC_API_BASE
}
}
})
3. In your module, you can then access these values through the Nuxt instance:
export default defineNuxtModule({
setup(options, nuxt) {
// Access runtime config values
const apiSecret = nuxt.options.runtimeConfig.apiSecret
const apiBase = nuxt.options.runtimeConfig.public.apiBase

console.log('API Secret:', apiSecret)
console.log('API Base:', apiBase)
}
})
export default defineNuxtModule({
setup(options, nuxt) {
// Access runtime config values
const apiSecret = nuxt.options.runtimeConfig.apiSecret
const apiBase = nuxt.options.runtimeConfig.public.apiBase

console.log('API Secret:', apiSecret)
console.log('API Base:', apiBase)
}
})
If you're using the ready hook and the values aren't available yet, you might need to use an earlier hook in the Nuxt lifecycle. The setup function of your module runs earlier than the ready hook, so you might have better luck accessing environment variables there. Also, make sure your environment variables follow the correct naming convention with the NUXT_ prefix as mentioned in the Runtime Config documentation. If you're still having issues, you could try explicitly loading the .env file in your module:
import { defineNuxtModule } from '@nuxt/kit'
import 'dotenv/config'

export default defineNuxtModule({
setup(options, nuxt) {
// Now process.env should have your .env variables
console.log(process.env.NUXT_MY_VARIABLE)

// Make sure to also set them in runtime config if needed
nuxt.options.runtimeConfig.myVariable = process.env.NUXT_MY_VARIABLE
}
})
import { defineNuxtModule } from '@nuxt/kit'
import 'dotenv/config'

export default defineNuxtModule({
setup(options, nuxt) {
// Now process.env should have your .env variables
console.log(process.env.NUXT_MY_VARIABLE)

// Make sure to also set them in runtime config if needed
nuxt.options.runtimeConfig.myVariable = process.env.NUXT_MY_VARIABLE
}
})
Remember that in production, .env files are not automatically loaded, and you'll need to set environment variables through your hosting platform as explained in the Environment Variables documentation. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5d ago
<@139883350096740354> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
dmarr
dmarrOP5d ago
@kapa.ai is there a way to know when you are in a build script vs dev server inside a module?
kapa.ai
kapa.ai5d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- Yes, inside a Nuxt module, you can determine whether you're running in a build script or development server using several methods: 1. Using nuxt.options.dev property:
export default defineNuxtModule({
setup(options, nuxt) {
// Check if we're in development mode
if (nuxt.options.dev) {
console.log('Running in development mode')
} else {
console.log('Running in production build mode')
}
}
})
export default defineNuxtModule({
setup(options, nuxt) {
// Check if we're in development mode
if (nuxt.options.dev) {
console.log('Running in development mode')
} else {
console.log('Running in production build mode')
}
}
})
2. Using import.meta.dev: According to the documentation, you can use the statically injected import.meta.dev property which is specifically designed for this purpose:
if (import.meta.dev) {
// Code that runs only during development
} else {
// Code that runs during production build
}
if (import.meta.dev) {
// Code that runs only during development
} else {
// Code that runs during production build
}
This is mentioned in the Import meta documentation, which states that import.meta.dev is "True when running the Nuxt dev server." The import.meta properties are statically injected and can be used for tree-shaking your runtime code, making them ideal for conditionally executing code based on the environment. Additionally, you can check if you're running a specific command like nuxi build vs nuxi dev by examining the Nuxt interface, which is created when you start Nuxt in development mode or when building a production application. These approaches allow you to write environment-specific code in your modules, ensuring that certain operations only run during development or build time. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5d ago
<@139883350096740354> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?