How to Build a Google Cloud Function Example for NodeJS with YAML secrets, CORS, and local testing
This is an example starter codebase for launching a cloud function into Google Cloud Platform (GCP). Learn more about cloud functions at https://cloud.google.com/functions/. This cloud function is written in NodeJS v8.
This README serves as a tutorial on how to launch your first cloud function with Node JS. Conducted on macOS Mojave. Run through can be done in 15 minutes.
No time for a for a tutorial? Jump right into the code base: https://github.com/zesty-io/google-cloud-function-node-example
Why Zesty.io made this Tutorial
Zesty.io is a cloud headless content management system. Integrations are extensions are often made leveraging cloud functions. At Zesty.io we use cloud functions for many of our side services, and really enjoy their quick deployment, reliability, and cheap cost structure.
Getting Started
Setting up your Environment
Create a Google Cloud account and create a project (
MY_PROJECTwill be used as an example)Download and install Google Cloud SDK https://cloud.google.com/sdk/docs/quickstarts and from your terminal run
gcloud auth loginInstall NodeJS https://nodejs.org/en/
Install Node Version Manager (NVM) from your terminal run
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bashin your terminalInstall GCP functions emulator for local testing by running
npm install -g @google-cloud/functions-emulatorin your terminalSetting functions emulator
functions config set projectId MY_PROJECT, and runfunctions start(OPTIONAL)Install Postman to make test requests the cloud function (rather than using your browser)
Setting up your project
You are going to use your terminal to run most commands.
Create a new directory on your computer e.g.
mkdir ./my-cloud-functionrun
cd ./my-cloud-functionto open the directoryrun
npm initand fill out the init question prompted in terminal, defaults are finerun
npm install corsinstalls a package we will use to control cross origin resource sharingrun
npm install env-yamlinstalls a package to read a local yaml file with secretsrun
nvm use v8to use node8run
echo "v8" > .nvmrcto create an nvm file to always use node 8 when you open the directoryrun
touch .env.yamlto create your base secret filerun
echo ".env.yaml" > .gitignoreto create a file that tells git not to commit secrets (security reasons)run
touch index.jsto create your base javascript file
Coding NodeJS in the Index.js file
index.js
run
code .oratom .to open the directory in your code editoropen
.env.yamland add this lineTEST_SECRET: hello worldwhich creates a secret stringTEST_SECRETopen
index.jsand add this code:
require('env-yaml').config({ path: './.env.yaml' })
console.log(process.env.TEST_SECRET)
this code will load up your secret file and output a secret to console
run
node index.jsto seehello worldoutputted to the terminal. At this point if you are running into errors, trace back to the Getting Starting section and walk through every step again.open
index.jsand replace all the code your wrote with:
require('env-yaml').config({ path: './.env.yaml' })
exports.myFunction = (req, res) => {
const cors = require('cors')()
cors(req, res, () => {
myFunction(req, res)
})
}
const myFunction = async (req, res) => {
res.send(process.env.TEST_SECRET)
}
Now you are ready to test!
Deploying locally
run
functions deploy myFunction --env-vars-file .env.yaml --trigger-httpwhich will create a local testable function, if this ran successfully, it will return you a url for your function, mine washttp://localhost:8010/my-project/us-central1/myFunction, to test the function copy that url.open your function url in a web browser, you should see "hello world"
If these steps failed you, you need to check your environment setup be going over easy step in getting started.
Deploying to the Google Cloud Platform
run
gcloud functions deploy myFunction --trigger-http --project=my-project --env-vars-file .env.yaml --runtime=nodejs8 --memory=256mb --timeout=240s"it should take 2 minutes to deploy, once deployed the terminal will display a URL to load it from remote, open that in your browser.
Success!
By Randy Apuzzo
Randy has had a penchant for computer programming from an early age and started applying his skills to build business software in 2004. Randy's stack of skills range from programming, system architecture, business know-how, to typographic design; which lends to a truly customer-centric and business effective software design. He leads the Zesty.io team as CEO.