Using .env Variables in Nuxt 2 or 3
When incorporating external configurations into Nuxt, it's necessary to leverage the .env file, where sensitive data can be stored and referenced later in the Nuxt configuration. Here's a comprehensive guide on achieving this.
In Nuxt 2.13 and above, .env support is built-in. To utilize it, follow these steps:
Define your variables, such as:
MY_VARIABLE="Hello World"
In your nuxt.config.js, import the .env values into the publicRuntimeConfig or privateRuntimeConfig objects:
export default { publicRuntimeConfig: { myPublicVariable: process.env.MY_VARIABLE, }, privateRuntimeConfig: { myPrivateVariable: process.env.MY_PRIVATE_VARIABLE, }, }
In Nuxt 3, the process is slightly different:
In nuxt.config.js:
import { defineNuxtConfig } from 'nuxt3' export default defineNuxtConfig({ runtimeConfig: { public: { myPublicVariable: process.env.MY_VARIABLE, }, }, })
In any component:
<script setup lang="ts"> const config = useRuntimeConfig() config.myPublicVariable </script>
In composables:
export default () => { const config = useRuntimeConfig() console.log(config.myPublicVariable) }
When defining variables in your .env file, remember to avoid using spaces and special characters. For example:
API_URL=https://example.com/api
Now, you can effortlessly access these variables anywhere in your Nuxt application. If facing any issues, consult the official Nuxt documentation for further guidance.
The above is the detailed content of How to Use .env Variables in Nuxt 2 and 3?. For more information, please follow other related articles on the PHP Chinese website!