Location>code7788 >text

Configuration and Use of Environment Variables

Popularity:499 ℃/2024-07-25 16:01:39

title: Configuring and Using Environment Variables
date: 2024/7/25
updated: 2024/7/25
author: cmdragon

excerpt:
Abstract: "The paper explores the detailed process of environment variable configuration under the framework, covering .env file configuration, runtime access, security considerations, practices in different scenarios (e.g., Vue apps, plugins, server routing), and best practices in multi-environment configurations."

categories:

  • front-end development

tags:

  • environment variable
  • configuration management
  • Runtime Configuration
  • security
  • TypeScript
  • Multi-environment deployment

image
image

scanningtwo-dimensional barcodeFollow or microsoft search:Programming Intelligence Front-End to Full-Stack Communication and Growth

Environment variables are a common way to configure applications, especially when managing different configuration values in different environments (e.g., development, test, production). In the
environment variables can be set with the.envfile to set it up and read it in the application. The following summarizes and explains the information you have provided:

Environment Variable Configuration

  1. .envfile

    • The Nuxt CLI supports reading during development, build, and generation..envDocumentation.
    • When running the built server, it will not read the.envDocumentation.
  2. Environment Variable Requirements

    • The variable must be in theis defined in order to avoid direct exposure of environment variables to the application code.
    • Only withNUXT_environment variables that start with uppercase and use the_Key-separated and case-variant environment variables can override runtime configuration properties.
  3. typical example

    • .envFile contents:

      NUXT_API_SECRET=api_secret_token
      NUXT_PUBLIC_API_BASE=
      
      
    • Configuration:

      export default defineNuxtConfig({
        runtimeConfig: {
          apiSecret: '', // can be overridden by the NUXT_API_SECRET environment variable
          public: {
            apiBase: '', // can be overridden by NUXT_PUBLIC_API_BASE environment variable
          }
        }, }
      }).
      
      

Read Runtime Configuration

  1. In a Vue application

    • utilizationuseRuntimeConfig()method to access the runtime configuration.
    • On the client side, only theThe keys in are available and are writable and responsive.
    • On the server side, the entire runtime configuration is available, but it is read-only.
  2. typical example

    • pages/Page:

      <script setup>
      const config = useRuntimeConfig()
      
      ('Runtime configuration:', config)
      if () {
        ('API key:', )
      }
      </script>
      
      <template>
        <div>
          <div> Please check the developer console! </div>.
        </div>
      </template>
      

Security tips

  • Do not render or pass to theuseStateto expose the runtime configuration keys to the client.

Runtime configuration is used in the plugin

  • In a custom plugin, thedefineNuxtPluginFunctions internally use theuseRuntimeConfig()

  • Example:plugins/

    export default defineNuxtPlugin((nuxtApp) => {
      const config = useRuntimeConfig()
    
      ('API infrastructural URL:', )
    });
    
    

Using Runtime Configuration in Server Routing

  • In server routing, you can use theuseRuntimeConfigAccess to the runtime configuration.

  • Example:server/api/

    export default defineEventHandler(async (event) => {
      const { apiSecret } = useRuntimeConfig(event)
      const result = await $fetch('/test', {
        headers: {
          Authorization: `Bearer ${apiSecret}`
        }
      })
      return result
    })
    
    

Type definitions for runtime configurations

  • Nuxt tries to generate TypeScript interfaces automatically, but types can also be added manually.

  • Example:

    declare module 'nuxt/schema' {
      interface RuntimeConfig {
        apiSecret: string
      }
      interface PublicRuntimeConfig {
        apiBase: string
      }
    }
    // It's important to make sure you always import/export something when augmenting the type
    export {}
    

Specify configurations for different environments

Creating custom environment files

First, you need to create a custom environment file such as `. `. This file should contain the environment variables you wish to use in your development environment.

``.
# .
MY_VARIABLE=my_value

```

utilization--dotenvParameters to start the Nuxt Development Server

utilizationnpx nuxi dev --dotenv .command to start the Nuxt Development Server and specify the environment file to be loaded as the.

```
npx nuxi dev --dotenv .

```

This command does the following:

- Loads the `. ` ` file with environment variables.
- Add these environment variables to the `` object.
- Starts the Nuxt Development Server.

Automatic restart mechanism

In development mode, Nuxt will monitor the.file changes. If you modify the.file and save it, Nuxt automatically detects the changes and restarts the development server to apply the new environment variable values.

This means that you don't need to manually restart your server, Nuxt does this automatically, ensuring that your environment variables are always up to date.

typical example

Suppose you have a.file, which reads as follows:

# .
API_URL=http://localhost:3000/api
DEBUG_MODE=true

You can start the Nuxt Development Server with the following command:

npx nuxi dev --dotenv .

During development, if you modify the.file, e.g. by placing theDEBUG_MODEchange intofalse

# .
API_URL=http://localhost:3000/api
DEBUG_MODE=false

After saving the file, Nuxt automatically detects the changes and restarts the server to make the new environment variables take effect.

i . changed, restarting server...
i server restarted.

For the rest of the article, please click to jump to the personal blog page or scan the code to follow or WeChat search:Programming Intelligence Front-End to Full-Stack Communication and Growth, read the full article: Configuring and Using Environment Variables | cmdragon's Blog

Past articles are archived:

  • Data fetching in server-side rendering: combining useRequestHeaders and useFetch | cmdragon's Blog
  • Accessing Request Events with the useRequestEvent Hook | cmdragon's Blog
  • Efficient Data Acquisition and Management with useNuxtData | cmdragon's Blog
  • Nuxt 3 User Guide: Getting to grips with useNuxtApp and the runtime context | cmdragon's Blog
  • Asynchronous Data Fetching with useLazyFetch | cmdragon's Blog
  • Enhancing the data loading experience with useLazyAsyncData | cmdragon's Blog
  • Using useHydration for Data Hydration and Synchronization | cmdragon's Blog
  • useHeadSafe: Generating HTML Head Elements Safely | cmdragon's Blog
  • Header Magic: Easily Customize Page Meta Information to Improve User Experience | cmdragon's Blog
  • Exploring useFetch: A Guide to Efficient Data Acquisition and Processing | cmdragon's Blog
  • Error Detective: useError Combined Functions | cmdragon's Blog
  • useCookie function: Managing cookies in an SSR environment | cmdragon's Blog
  • Easy to master useAsyncData to get asynchronous data | cmdragon's Blog
  • Using useAppConfig: Managing Application Configuration with Ease | cmdragon's Blog
  • Nuxt Framework Built-in Components Explained and Usage Guide (V) | cmdragon's Blog
  • Nuxt Framework Built-in Components Explained and Usage Guide (4) | cmdragon's Blog
  • Nuxt Framework Built-in Components Explained and Usage Guide (3) | cmdragon's Blog