Google Apps Script environment variables


This post goes over how to store environment variables with Google Apps Script.

Prerequisites

Create a Google Apps Script in one of two ways:

  1. Google Drive > New > More > Google Apps Script
  2. Google Sheets > Extensions > Apps Scripts

Script Properties

Add a script property:

  1. Apps Script > Project Settings > Script Properties > Add script property

Google Apps Script

Get all properties:

function getEnv() {
  return PropertiesService.getScriptProperties().getProperties();
}

console.log(getEnv());

Get property value by name:

function getEnv(key) {
  return PropertiesService.getScriptProperties().getProperty(key);
}

console.log(getEnv('MY_SECRET_KEY'));

Script

Here’s a reusable script to fetch JSON:

/**
 * @param {string|undefined} key
 * @returns {string|null|object}
 */
function getEnv(key) {
  if (key) {
    return PropertiesService.getScriptProperties().getProperty(key);
  }
  return PropertiesService.getScriptProperties().getProperties();
}

And it can be called like so:

// get all properties
const properties = getEnv();
console.log(properties);

// get single property
const value = getEnv('MY_SECRET_KEY');
console.log(value);


Please support this site and join our Discord!