Skip to content

$env

The $env tool provides a unified way to access environment variables and runtime configuration in your Nuxt application. It combines process environment variables with Nuxt's runtime configuration system.

Features

  • Environment detection with dev, prod, and test flags
  • Server configuration access (port, host, baseURL)
  • Nuxt runtime config integration for public configuration
  • Type-safe access to environment variables
  • Cached configuration for performance

API Reference

$env()

Returns the combined environment configuration including base environment variables and Nuxt runtime config.

Returns: $Env<T> - Environment configuration object

ts
import { $env } from '#appkit/tools'

const env = $env()

// Environment flags
console.log(env.public.dev)     // true in development
console.log(env.public.prod)    // true in production  
console.log(env.public.test)    // true in test mode

// Server configuration
console.log(env.public.port)    // Server port (default: 3000)
console.log(env.public.host)    // Server host (default: "localhost")
console.log(env.public.baseURL) // Base URL (default: "/")

// Access any public runtime config
console.log(env.apiUrl)         // Custom config from nuxt.config.ts

Base Environment Variables

The $env tool automatically provides these standardized environment variables:

Environment Flags

PropertyTypeDescriptionDefault
devbooleanTrue in development modeNODE_ENV === "development"
prodbooleanTrue in production modeNODE_ENV === "production"
testbooleanTrue in test modeNODE_ENV === "test"

Server Configuration

PropertyTypeDescriptionDefault
portnumberServer port numberPORT env var or 3000
hoststringServer hostnameHOST env var or "localhost"
baseURLstringApplication base URLBASE_URL env var or "/"

Usage Examples

Environment-Based Logic

ts
import { $env } from '#appkit/tools'

const env = $env()

// Conditional behavior based on environment
if (env.public.dev) {
  console.log('Development mode - enabling debug features')
}

if (env.public.prod) {
  // Production-only configuration
  console.log('Production mode - optimizing performance')
}

// Different API endpoints per environment
const apiUrl = env.public.dev 
  ? 'http://localhost:3001/api'
  : 'https://api.example.com'

Server Configuration

ts
import { $env } from '#appkit/tools'

const env = $env()

// Build URLs dynamically
const fullUrl = `http://${env.public.host}:${env.public.port}${env.public.baseURL}`

// Configure services
const serverConfig = {
  port: env.public.port,
  host: env.public.host,
  baseURL: env.public.baseURL
}

Integration with Nuxt Runtime Config

In your nuxt.config.ts, define public runtime configuration:

ts
// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    // Private keys (only available on server-side)
    apiSecret: process.env.NUXT_API_SECRET,
    
    // Public keys (exposed to client-side)
    public: {
      apiUrl: process.env.NUXT_PUBLIC_API_URL,
      appName: 'My App',
      version: '1.0.0'
    }
  }
})

Then access them through $env():

ts
import { $env } from '#appkit/tools'

const env = $env()

// Access custom public config
console.log(env.apiUrl)   // From NUXT_PUBLIC_API_URL
console.log(env.appName)  // "My App"
console.log(env.version)  // "1.0.0"

Type Safety

Define custom environment types for better TypeScript support:

ts
// types/env.d.ts
declare module '#appkit/tools' {
  interface $Env {
    apiUrl: string
    appName: string
    version: string
    featureFlags: {
      newDashboard: boolean
      betaFeatures: boolean
    }
  }
}

Then use with full type safety:

ts
import { $env } from '#appkit/tools'

const env = $env()

// TypeScript knows about your custom properties
const isNewDashboardEnabled = env.featureFlags.newDashboard

Advanced Usage

Feature Flags

ts
import { $env } from '#appkit/tools'

const env = $env()

// Environment-based feature flags
const features = {
  analytics: env.public.prod,
  debugging: env.public.dev,
  testing: env.public.test,
  betaFeatures: env.betaFeatures || env.public.dev
}

// Use in components
if (features.analytics) {
  // Initialize analytics
}

Configuration Validation

ts
import { $env } from '#appkit/tools'
import { $assert } from '#appkit/tools'
import { type } from 'arktype'

const configValidator = type({
  public: {
    dev: "boolean",
    prod: "boolean",
    port: "number",
    host: "string"
  },
  apiUrl: "string.url"
})

const env = $env()
const validation = $assert(env, configValidator)

if (!validation.success) {
  throw new Error(`Invalid environment configuration: ${validation.error}`)
}

Environment-Specific Imports

ts
import { $env } from '#appkit/tools'

const env = $env()

// Dynamically import based on environment
const logger = env.public.dev 
  ? await import('./dev-logger')
  : await import('./prod-logger')

const analytics = env.public.prod
  ? await import('./analytics')
  : { track: () => {} } // No-op in development

Performance

The $env function uses internal caching to avoid repeated configuration lookups:

  • First call initializes and caches the configuration
  • Subsequent calls return the cached configuration
  • Configuration is computed once per application lifecycle

Best Practices

  1. Access Once: Call $env() once and store the result if used frequently
  2. Type Definitions: Define custom types for your environment variables
  3. Validation: Validate critical environment variables on startup
  4. Environment Flags: Use the provided dev/prod/test flags instead of checking NODE_ENV directly
  5. Public Config: Use Nuxt's public runtime config for client-accessible variables
  6. Sensitive Data: Never expose sensitive data through public runtime config
  • Nuxt Runtime Config: Built on top of Nuxt's useRuntimeConfig()
  • $assert: Can be used to validate environment configuration
  • Process Environment: Integrates with standard Node.js environment variables