#env variables vs runtime config on server code
3 messages · Page 1 of 1 (latest)
The behavior you're experiencing with environment variables in Nuxt on AWS App Runner highlights an important distinction between how environment variables work in development versus production environments.
Environment Variables vs Runtime Config
In Nuxt, there are two main ways to access configuration values:
- Direct environment variables (
process.env.*) - Runtime config (
useRuntimeConfig())
The key difference is that .env files are automatically loaded during development and build time, but not in production runtime. As explained in the documentation:
Nuxi CLI has built-in support for reading your
.envfile in development, build and generate. But when you run your built server, your.envfile will not be read. Runtime Config
What's Happening in Your Code
For your google.ts utility, there are a few possible explanations for why it works:
- The environment variables might be set directly in your AWS App Runner configuration
- The values might be getting baked into the build at build time (though you mentioned not finding evidence of this)
- The code path might not actually be executing the validation function in production
For your stripe.ts utility that's failing, it's likely because:
- It's trying to access
process.env.STRIPE_SECRET_KEYdirectly at runtime - This environment variable isn't available in the production environment
The Solution: Use Runtime Config
The recommended approach for handling environment variables in Nuxt is to use the runtime config system:
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
// Server-side only variables
googleClientId: process.env.GOOGLE_CLIENT_ID || '',
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
googleRedirectUri: process.env.GOOGLE_REDIRECT_URI || '',
stripeSecretKey: process.env.STRIPE_SECRET_KEY || '',
// Variables exposed to client
public: {
// Any public variables here
}
}
})
Then in your server utilities:
// server/utils/google.ts
export function getOAuth2Client() {
const config = useRuntimeConfig()
if (!config.googleClientId || !config.googleClientSecret || !config.googleRedirectUri) {
throw new Error('Google OAuth configuration is missing')
}
return new OAuth2Client({
clientId: config.googleClientId,
clientSecret: config.googleClientSecret,
redirectUri: config.googleRedirectUri,
})
}
This approach ensures your environment variables are properly passed to your application at runtime, even in serverless or edge environments like AWS App Runner.