Skip to content

Commit 8a938db

Browse files
committed
fix: env not being picked up always
1 parent 5a8e644 commit 8a938db

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/module.ts

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,9 @@ const REGISTRY_ENV_DEFAULTS: Partial<Record<RegistryScriptKey, Record<string, st
138138
xPixel: { id: '' },
139139
}
140140

141+
const UPPER_RE = /([A-Z])/g
142+
const toScreamingSnake = (s: string) => s.replace(UPPER_RE, '_$1').toUpperCase()
143+
141144
const PARTYTOWN_FORWARDS: Partial<Record<RegistryScriptKey, string[]>> = {
142145
bingUet: ['uetq.push'],
143146
googleAnalytics: ['dataLayer.push', 'gtag'],
@@ -341,14 +344,27 @@ export default defineNuxtModule<ModuleOptions>({
341344
nuxt.options.runtimeConfig.public = nuxt.options.runtimeConfig.public || {}
342345

343346
// Auto-populate env var defaults for enabled registry scripts so that
344-
// NUXT_PUBLIC_SCRIPTS_<SCRIPT>_<KEY> works without manual runtimeConfig
347+
// NUXT_PUBLIC_SCRIPTS_<SCRIPT>_<KEY> works without manual runtimeConfig.
348+
// Nuxt resolves env vars against runtimeConfig before modules run, so if the
349+
// user didn't declare the path, env vars are silently dropped. We read
350+
// process.env directly to recover them.
345351
const registryWithDefaults: Record<string, any> = {}
346352
for (const [key, entry] of Object.entries(config.registry)) {
347353
if (entry === false)
348354
continue
349355
const input = (entry as any[])[0]
350356
const envDefaults = REGISTRY_ENV_DEFAULTS[key as RegistryScriptKey]
351-
registryWithDefaults[key] = envDefaults ? defu(input, envDefaults) : input
357+
if (!envDefaults) {
358+
registryWithDefaults[key] = input
359+
continue
360+
}
361+
// Read process.env for each field, falling back to the static default
362+
const envResolved: Record<string, string> = {}
363+
for (const [field, defaultValue] of Object.entries(envDefaults)) {
364+
const envKey = `NUXT_PUBLIC_SCRIPTS_${toScreamingSnake(key)}_${toScreamingSnake(field)}`
365+
envResolved[field] = process.env[envKey] || defaultValue
366+
}
367+
registryWithDefaults[key] = defu(input, envResolved)
352368
}
353369

354370
nuxt.options.runtimeConfig.public.scripts = defu(

0 commit comments

Comments
 (0)