How to deploy node.js functions to Google Cloud.

Get started with Node & GCP

The serverless trend is the latest evolution of network application architecture. You no longer need to think about the hardware, the OS, or even the running application. Deploy nothing more than the lines of code you need to run wrapped in a node.js function.

Initializing gcloud

Run gcloud init to set up your environment configuration. gcloud will need a name for the current configuration, enter whatever you want. If you've run this before you'll have the ability to reinitialize, switch configurations, or create a new configuration. Choose whatever is appropriate.

Enabling Google Cloud Functions API

Getting started with any of the GCP services requires that you enable the APIs individually. This comes with billing implications so make sure you understand what you enable and what you deploy! For the functions we will deploy there is not much risk but there are services that are deceptively easy to deploy. Some deployments can run you hundreds of dollars in charges even when idle. I’m looking at you Dataflow.

Creating a basic http functions

Google cloud functions are handlers in an Express application and you can do anything in them you’d expect to be able to do in an Express app. The basic function signature takes in a request and response object. Sending a response is handled via the response object.

$ npm init -y
exports.myFunction = (req, res) => {
res.send(`<h1>You're awesome 🤘</h1>`);
};

Testing with the functions emulator

Before deploying it’s important to test locally. Deploying takes time and disrupts the development cycle considerably. You can deploy locally with the GCP Functions Emulator.

$ npm install -g @google-cloud/functions-emulator
functions deploy myFunction --trigger-http

Deploying to Google Cloud

Using gcloud to deploy functions is similar to using the functions command line tool except we also need to explicitly specify the runtime, e.g. nodejs8 or nodejs10.

$ gcloud functions deploy myFunction --trigger-http --runtime=nodejs8

Other types of functions

HTTP functions are an obvious first foray into GCP’s functions but you can use cloud functions for a lot more. Look into Google’s Pub/Sub for an extensible way of tying messages into pipelines filled with functions. You can use Google’s Cloud Scheduler to periodically kick off Pub/Sub messages that trigger cloud functions. You can even use Chrome itself inside Google Cloud Functions allowing you to set up an automatic web scraper that dumps results to a database with little more than a handful of GCP services.

I write about JavaScript, Reverse Engineering, Security, and Credential Stuffing. Also a speaker, O'Reilly Author, creator of Plato, Director at Shape Security.