Skip to Content

Using Environment Variables

Published: 2022-06-27

It's very common that you don't want to put secrets into your configuration files as these could be stored in a git repository. Additionally, you might want to change the behaviour of WunderGraph depending on the environment where it's being deployed.

To solve these two problems, you're able to use Environment Variables within the WunderGraph configuration. This way, we don't statically embed a secret or variable into the generated configuration. Instead, we put instructions into the config to resolve the variables at startup time.

Here's an example.

Regular static configuration#

This configuration introspects the spacex API using a static string as the URL. This string will be statically embedded into the WunderGraph configuration and cannot be changed at runtime.

const spaceX = introspect.graphql({
apiNamespace: "spacex",
url: "https://api.spacex.land/graphql/",
});

Configuration using an Environment Variable#

This example pulls the URL for the spacex API from an environment variable. At runtime, you can pass another URL to the WunderGraph environment to use another URL to talk to the origin. Keep in mind that introspection only happens during development, not in production. The only thing that's changing is the URL.

import {EnvironmentVariable} from "@wundergraph/sdk";
const spaceX = introspect.graphql({
apiNamespace: "spacex",
url: new EnvironmentVariable("SPACEX_GRAPHQL_URL"),
});

Configuration using an Environment Variable with a default fallback#

In some scenarios, you want to use an Environment Variable but also provide a fallback. This means, the default value will be embedded into the configuration, but if an environment variable is present at startup time, it will take precedence over the default value.

import {EnvironmentVariable} from "@wundergraph/sdk";
const spaceX = introspect.graphql({
apiNamespace: "spacex",
url: new EnvironmentVariable("SPACEX_GRAPHQL_URL","https://api.spacex.land/graphql/"),
});

Loading Environment Variables from a dot env file#

As you've learned, it's very easy to use Environment Variables from within WunderGraph. Aside from setting Environment Variables manually, there's also an additional way of populating them, .env files!

You might be working with different environments and want to use .env files to implement this strategy. Using .env files is straight foward with WunderGraph.

By default, wunderctl loads all variables from the .env file in the current working directory. Environment Variables that already exist on the global environment take precedence over the .env file variables. It's also possible to specify a custom file, e.g. when using multiple environments.

wunderctl up --env .env.prod

Product

Comparisons

Subscribe to our newsletter!

Stay informed when great things happen! Get the latest news about APIs, GraphQL and more straight into your mailbox.

© 2022 WunderGraph