Using environment variables
यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।
Astro gives you access to Vite’s built-in environment variables support and includes some default environment variables for your project that allow you to access configuration values for your current project (e.g. site, base), whether your project is running in development or production, and more.
Astro also provides a way to use and organize your environment variables with type safety. It is available for use inside the Astro context (e.g. Astro components, routes and endpoints, UI framework components, middleware), and managed with a schema in your Astro configuration.
Vite’s built-in support
Section titled Vite’s built-in supportAstro uses Vite’s built-in support for environment variables, which are statically replaced at build time, and lets you use any of its methods to work with them.
Note that while all environment variables are available in server-side code, only environment variables prefixed with PUBLIC_ are available in client-side code for security purposes.
SECRET_PASSWORD=password123PUBLIC_ANYBODY=thereIn this example, PUBLIC_ANYBODY (accessible via import.meta.env.PUBLIC_ANYBODY) will be available in server or client code, while SECRET_PASSWORD (accessible via import.meta.env.SECRET_PASSWORD) will be server-side only.
.env files are not loaded inside configuration files.
IntelliSense for TypeScript
Section titled IntelliSense for TypeScriptBy default, Astro provides a type definition for import.meta.env in astro/client.d.ts.
While you can define more custom env variables in .env.[mode] files, you may want to get TypeScript IntelliSense for user-defined env variables which are prefixed with PUBLIC_.
To achieve this, you can create an env.d.ts in src/ and configure ImportMetaEnv like this:
interface ImportMetaEnv { readonly DB_PASSWORD: string; readonly PUBLIC_POKEAPI: string; // more env variables...}
interface ImportMeta { readonly env: ImportMetaEnv;}Default environment variables
Section titled Default environment variablesAstro includes a few environment variables out of the box:
import.meta.env.MODE: The mode your site is running in. This isdevelopmentwhen runningastro devandproductionwhen runningastro build.import.meta.env.PROD:trueif your site is running in production;falseotherwise.import.meta.env.DEV:trueif your site is running in development;falseotherwise. Always the opposite ofimport.meta.env.PROD.import.meta.env.BASE_URL: The base URL your site is being served from. This is determined by thebaseconfig option.import.meta.env.SITE: This is set to thesiteoption specified in your project’sastro.config.import.meta.env.ASSETS_PREFIX: The prefix for Astro-generated asset links if thebuild.assetsPrefixconfig option is set. This can be used to create asset links not handled by Astro.
Use them like any other environment variable.
const isProd = import.meta.env.PROD;const isDev = import.meta.env.DEV;Setting environment variables
Section titled Setting environment variables.env files
Section titled .env filesEnvironment variables can be loaded from .env files in your project directory.
Just create a .env file in the project directory and add some variables to it.
# This will only be available when run on the server!DB_PASSWORD="foobar"
# This will be available everywhere!PUBLIC_POKEAPI="https://pokeapi.co/api/v2"You can also add .production, .development or a custom mode name to the filename itself (e.g .env.testing, .env.staging). This allows you to use different sets of environment variables at different times.
The astro dev and astro build commands default to "development" and "production" modes, respectively. You can run these commands with the --mode flag to pass a different value for mode and load the matching .env file.
This allows you to run the dev server or build your site connecting to different APIs:
# Run the dev server connected to a "staging" APInpm run astro dev -- --mode staging
# Build a site that connects to a "production" API with additional debug informationnpm run astro build -- --devOutput
# Build a site that connects to a "testing" APInpm run astro build -- --mode testing# Run the dev server connected to a "staging" APIpnpm astro dev --mode staging
# Build a site that connects to a "production" API with additional debug informationpnpm astro build --devOutput
# Build a site that connects to a "testing" APIpnpm astro build --mode testing# Run the dev server connected to a "staging" APIyarn astro dev --mode staging
# Build a site that connects to a "production" API with additional debug informationyarn astro build --devOutput
# Build a site that connects to a "testing" APIyarn astro build --mode testingFor more on .env files, see the Vite documentation.
In the Astro config file
Section titled In the Astro config fileAstro evaluates configuration files before it loads your other files. This means that you cannot use import.meta.env in astro.config.mjs to access environment variables that were set in .env files.
You can use process.env in a configuration file to access other environment variables, like those set by the CLI.
You can also use Vite’s loadEnv helper to manually load .env files.
import { loadEnv } from "vite";
const { SECRET_PASSWORD } = loadEnv(process.env.NODE_ENV, process.cwd(), "");pnpm does not allow you to import modules that are not directly installed in your project. If you are using pnpm, you will need to install vite to use the loadEnv helper.
pnpm add -D viteUsing the CLI
Section titled Using the CLIYou can also add environment variables as you run your project:
PUBLIC_POKEAPI=https://pokeapi.co/api/v2 npm run devPUBLIC_POKEAPI=https://pokeapi.co/api/v2 pnpm run devPUBLIC_POKEAPI=https://pokeapi.co/api/v2 yarn run devGetting environment variables
Section titled Getting environment variablesEnvironment variables in Astro are accessed with import.meta.env, using the import.meta feature added in ES2020, instead of process.env.
For example, use import.meta.env.PUBLIC_POKEAPI to get the PUBLIC_POKEAPI environment variable.
// When import.meta.env.SSR === trueconst data = await db(import.meta.env.DB_PASSWORD);
// When import.meta.env.SSR === falseconst data = fetch(`${import.meta.env.PUBLIC_POKEAPI}/pokemon/squirtle`);When using SSR, environment variables can be accessed at runtime based on the SSR adapter being used. With most adapters you can access environment variables with process.env, but some adapters work differently. For the Deno adapter, you will use Deno.env.get(). See how to access the Cloudflare runtime to handle environment variables when using the Cloudflare adapter. Astro will first check the server environment for variables, and if they don’t exist, Astro will look for them in .env files.
Type safe environment variables
Section titled Type safe environment variablesThe astro:env API lets you configure a type-safe schema for environment variables you have set. This allows you to indicate whether they should be available on the server or the client, and define their data type and additional properties.
astro:env.
Basic Usage
Section titled Basic UsageDefine your schema
Section titled Define your schemaTo configure a schema, add the env.schema option to your Astro config:
import { defineConfig } from "astro/config";
export default defineConfig({ env: { schema: { // ... } }})You can then register variables as a string, number, enum, or boolean using the envField helper. Define the kind of environment variable by providing a context ("client" or "server") and access ("secret" or "public") for each variable, and pass any additional properties such as optional or default in an object:
import { defineConfig, envField } from "astro/config";
export default defineConfig({ env: { schema: { API_URL: envField.string({ context: "client", access: "public", optional: true }), PORT: envField.number({ context: "server", access: "public", default: 4321 }), API_SECRET: envField.string({ context: "server", access: "secret" }), } }})Types will be generated for you when running astro dev or astro build, but you can run astro sync to generate types only.
Use variables from your schema
Section titled Use variables from your schemaImport and use your defined variables from the appropriate /client or /server module:
---import { API_URL } from "astro:env/client";import { API_SECRET_TOKEN } from "astro:env/server";
const data = await fetch(`${API_URL}/users`, { method: "GET", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_SECRET_TOKEN}` },})---
<script> import { API_URL } from "astro:env/client";
fetch(`${API_URL}/ping`)</script>Variable types
Section titled Variable typesThere are three kinds of environment variables, determined by the combination of context ("client" or "server") and access ("secret" or "public") settings defined in your schema:
-
Public client variables: These variables end up in both your final client and server bundles, and can be accessed from both client and server through the
astro:env/clientmodule:import { API_URL } from "astro:env/client"; -
Public server variables: These variables end up in your final server bundle and can be accessed on the server through the
astro:env/servermodule:import { PORT } from "astro:env/server"; -
Secret server variables: These variables are not part of your final bundle and can be accessed on the server through the
astro:env/servermodule:import { API_SECRET } from "astro:env/server";By default, secrets are only validated at runtime. You can enable validating private variables on start by configuring
validateSecrets: true.
Secret client variables are not supported because there is no safe way to send this data to the client. Therefore, it is not possible to configure both context: "client" and access: "secret" in your schema.
Data types
Section titled Data typesThere are currently four data types supported: strings, numbers, enums, and booleans:
import { envField } from "astro/config";
envField.string({ // context & access optional: true, default: "foo",})
envField.number({ // context & access optional: true, default: 15,})
envField.boolean({ // context & access optional: true, default: true,})
envField.enum({ // context & access values: ["foo", "bar", "baz"], optional: true, default: "baz",})envField API reference.
Retrieving secrets dynamically
Section titled Retrieving secrets dynamicallyDespite defining your schema, you may want to retrieve the raw value of a given secret or to retrieve secrets not defined in your schema. In this case, you can use getSecret() exported from astro:env/server:
import { FOO, // boolean getSecret} from "astro:env/server";
getSecret("FOO"); // string | undefinedLimitations
Section titled Limitationsastro:env is a virtual module which means it can only be used inside the Astro context. For example, you can use it in:
- Middlewares
- Astro routes and endpoints
- Astro components
- Framework components
- Modules
You cannot use it in the following and will have to resort to process.env:
astro.config.mjs- Scripts