Nuxt/docs/2.guide/2.directory-structure/2.env.md

58 lines
2.6 KiB
Markdown
Raw Normal View History

---
title: ".env"
description: "A .env file specifies your build/dev-time environment variables."
head.title: ".env"
navigation.icon: i-ph-file-duotone
---
::important
This file should be added to your [`.gitignore`](/docs/guide/directory-structure/gitignore) file to avoid pushing secrets to your repository.
::
2023-07-30 09:16:45 +00:00
## Dev, Build and Generate Time
Nuxt CLI has built-in [dotenv](https://github.com/motdotla/dotenv) support in development mode and when running [`nuxi build`](/docs/api/commands/build) and [`nuxi generate`](/docs/api/commands/generate).
In addition to any process environment variables, if you have a `.env` file in your project root directory, it will be automatically loaded **at dev, build and generate time**. Any environment variables set there will be accessible within your `nuxt.config` file and modules.
```bash [.env]
MY_ENV_VARIABLE=hello
```
::note
Note that removing a variable from `.env` or removing the `.env` file entirely will not unset values that have already been set.
::
## Custom File
If you want to use a different file - for example, to use `.env.local` or `.env.production` - you can do so by passing the `--dotenv` flag when using `nuxi`.
```bash [Terminal]
npx nuxi dev --dotenv .env.local
```
When updating `.env` in development mode, the Nuxt instance is automatically restarted to apply new values to the `process.env`.
2023-07-30 09:16:45 +00:00
## Production Preview
**After your server is built**, you are responsible for setting environment variables when you run the server.
2023-07-30 09:16:45 +00:00
Your `.env` file will not be read at this point. How you do this is different for every environment.
For local production preview purpose, we recommend using [`nuxi preview`](/docs/api/commands/preview) since using this command, the `.env` file will be loaded into `process.env` for convenience. Note that this command requires dependencies to be installed in the package directory.
2023-07-30 09:16:45 +00:00
Or you could pass the environment variables as arguments using the terminal. For example, on Linux or macOS:
```bash [Terminal]
2023-07-30 09:16:45 +00:00
DATABASE_HOST=mydatabaseconnectionstring node .output/server/index.mjs
```
Note that for a purely static site, it is not possible to set runtime configuration config after your project is prerendered.
:read-more{to="/docs/guide/going-further/runtime-config"}
::note
If you want to use environment variables set at build time but do not care about updating these down the line (or only need to update them reactively _within_ your app) then `appConfig` may be a better choice. You can define `appConfig` both within your `nuxt.config` (using environment variables) and also within an `~/app.config.ts` file in your project.
:read-more{to="/docs/guide/directory-structure/app-config"}
::