Blog>
Snippets

Using environment variables in Edge functions

Explain how to access environment variables in Edge functions securely and how to differentiate between build-time and runtime variables.
exports.handler = async () => {
    // Accessing a build-time environment variable
    const buildTimeVar = process.env.BUILD_TIME_VARIABLE;
    console.log('Build-time variable:', buildTimeVar);

    // Accessing a runtime environment variable (assumes runtime variable support)
    const runtimeVar = process.env.RUNTIME_VARIABLE || 'default-value';
    console.log('Runtime variable:', runtimeVar);

    // Returning a simple response
    return new Response('Check the console logs for environment variables.');
};
This piece of code represents an Edge function that accesses both build-time and runtime environment variables. 'BUILD_TIME_VARIABLE' is accessed directly as it is available during the build phase, whereas 'RUNTIME_VARIABLE' may not be available, so a default value is provided as a fallback. The console will output these variable values. Finally, it returns a simple text response.
// Defining build-time environment variables in package.json
{
  "scripts": {
    "build": "BUILD_TIME_VARIABLE='myValue' node build.js"
  }
}
This code snippet shows how to set a build-time environment variable in the package.json file within the 'scripts' section. The 'build' script is setting 'BUILD_TIME_VARIABLE' to 'myValue' before running the build command.
// Load the .env file during development using dotenv for local testing
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
This code snippet demonstrates how to conditionally load environment variables from a .env file during development for local testing using the dotenv package. It will avoid loading the .env file in production.