Using environment variables in Azure Static Web App API and locally

The API code we created in Part 2 of the tutorial runs as an Azure Function and can access environment variables. What you would normally store here (and not client-side) are connection strings for accessing a database (e.g., MySQL), an Azure Storage resource (e.g., Blob or Tables) or external APIs (e.g., the Ably messaging service).

To access environment variables from the API code, we'll use the process global object, which has all the environment variables stored in the env property.

process.env.connectionString || "HARDCODED_CONN_STRING"


We'll be using three types of variables:

- a hard-coded one, used in code in the absence of any environment configuration: "HARDCODED_CONN_STRING"

- a local one for development, read from the global object: process.env.connectionString

This local value is set up in the local.settings.json file in the project root folder.

- a value configured in the Azure environment in the Static Web App configuration page. This is also accessed from process.env.connectionString.

Accessing the environment variable

Local environment settings

Azure settings

Getting the environment value based on current environment


Comments