This post goes over how to store environment variables with Google Apps Script.
Prerequisites
Create a Google Apps Script in one of two ways:
- Google Drive > New > More > Google Apps Script
- Google Sheets > Extensions > Apps Scripts
Script Properties
Add a script property:
- 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);