From 36dd8e55605149179f46e4bce59e7e4539a4132d Mon Sep 17 00:00:00 2001 From: AsyncBanana <58297401+AsyncBanana@users.noreply.github.com> Date: Wed, 20 Oct 2021 18:55:12 -0400 Subject: [PATCH] Add environment variables docs (Closes #873) (#1587) * Added environment variables docs (Closes #873) * Fixed prefix --- docs/src/config.ts | 1 + .../src/pages/guides/environment-variables.md | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 docs/src/pages/guides/environment-variables.md diff --git a/docs/src/config.ts b/docs/src/config.ts index ce757f7e1d4f..d7e2cbb55e5d 100644 --- a/docs/src/config.ts +++ b/docs/src/config.ts @@ -24,6 +24,7 @@ export const SIDEBAR = { { text: 'RSS', link: 'guides/rss' }, { text: 'Supported Imports', link: 'guides/imports' }, { text: 'Aliases', link: 'guides/aliases' }, + { text: 'Environment Variables', link: 'guides/environment-variables' }, { text: 'Deploy to the web', link: 'guides/deploy' }, { text: 'Publish to npm', link: 'guides/publish-to-npm' }, diff --git a/docs/src/pages/guides/environment-variables.md b/docs/src/pages/guides/environment-variables.md new file mode 100644 index 000000000000..1f7f396ad96c --- /dev/null +++ b/docs/src/pages/guides/environment-variables.md @@ -0,0 +1,29 @@ +--- +layout: ~/layouts/MainLayout.astro +title: Using environment variables +description: Learn how to use environment variables in an Astro project. +--- + +Astro uses Vite for environment variables, and allows you to use any of its methods to get and set environment variables. Note that all environment variables must be prefixed with `VITE_` to be accessible by client side code. + +## Setting environment variables + +Vite includes `dotenv` by default, allowing you to easily set environment variables with no configuration in Astro projects. You can also attach a mode (either `production` or `development`) to the filename, like `.env.production` or `.env.development`, which makes the environment variables only take effect in that mode. + +Just create a `.env` file in the project directory and add some variables to it. + +```bash +# .env +VITE_POKEAPI="https://pokeapi.co/api/v2" +``` + +## Getting environment variables + +Instead of using `process.env`, with Vite you use `import.meta.env`, which uses the `import.meta` feature added in ES2020 (don't worry about browser support though, Vite replaces all `import.meta.env` mentions with static values). For example, to get the `VITE_POKEAPI` environment variable, you could use `import.meta.env.VITE_POKEAPI`. + +```js +fetch(`${import.meta.env.VITE_POKEAPI}/pokemon/squirtle` +``` + +> ⚠️WARNING⚠️: +> Because Vite statically replaces `import.meta.env`, you cannot access it with dynamic keys like `import.meta.env[key]`.