Deploy HTTP Cloud Functions on Google Cloud with Node.js
Create and deploy HTTP-triggered Cloud Functions on Google Cloud with Node.js, Express integration, secrets management, and gcloud CLI deployment.
Overview
Cloud Functions is the serverless compute piece of Google Cloud: you ship a handler, and Google runs, scales and meters it. The 2nd generation (v2) sits on Cloud Run and Eventarc, with HTTP triggers, CloudEvent triggers and per-instance request concurrency. Below: creating HTTP-triggered functions with Node.js, wiring Express for routing, managing secrets with Secret Manager, and deploying with the gcloud CLI.
Runnable versions of the Express app, package.json, and the deploy scripts in this recipe live in the companion resources.
When to Use This
- Building serverless HTTP APIs on Google Cloud
- Webhooks and event-driven endpoints
- Lightweight microservices without managing infrastructure
- Integrating with GCP services (Firestore, Pub/Sub, Cloud Storage)
Skip Cloud Functions for CPU-bound work that outlives the 60-minute timeout, WebSockets, or stateful workloads. That’s Cloud Run territory, or GKE if you need full orchestration.
Prerequisites
- Node.js 18+
- Google Cloud CLI (
gcloud) - A GCP project with billing enabled
- Cloud Functions API enabled
Solution
1. Enable APIs and Set Up
# Set project
gcloud config set project my-project-id
# Enable required APIs
gcloud services enable cloudfunctions.googleapis.com
gcloud services enable cloudbuild.googleapis.com
gcloud services enable secretmanager.googleapis.com
2. Basic HTTP Function (Gen 2)
// index.js (Cloud Functions v2 — uses CloudEvents)
const functions = require('@google-cloud/functions-framework');
functions.http('helloWorld', (req, res) => {
const name = req.query.name || req.body?.name || 'World';
res.status(200).json({
message: `Hello, ${name}!`,
timestamp: new Date().toISOString(),
});
});
// package.json
{
"name": "my-cloud-function",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"@google-cloud/functions-framework": "^3.3.0"
}
}
3. Express Integration
// index.js
const functions = require('@google-cloud/functions-framework');
const express = require('express');
const app = express();
app.use(express.json());
// Routes — handlers must be async: Firestore calls return Promises,
// and forgetting await serializes a Promise instead of a user
app.get('/users/:id', async (req, res) => {
const user = await getUserFromDb(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
});
app.post('/users', async (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({ error: 'name and email are required' });
}
const user = await createUser({ name, email });
res.status(201).json(user);
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Register Express app as the function handler
functions.http('api', app);
4. Firestore Integration
const { Firestore } = require('@google-cloud/firestore');
const firestore = new Firestore();
async function getUserFromDb(userId) {
const doc = await firestore.collection('users').doc(userId).get();
if (!doc.exists) return null;
return { id: doc.id, ...doc.data() };
}
async function createUser(data) {
const docRef = await firestore.collection('users').add({
...data,
createdAt: Firestore.FieldValue.serverTimestamp(),
});
return { id: docRef.id, ...data };
}
5. Secrets Management with Secret Manager
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
const secretClient = new SecretManagerServiceClient();
async function getSecret(name) {
const [version] = await secretClient.accessSecretVersion({
name: `projects/my-project-id/secrets/${name}/versions/latest`,
});
return version.payload.data.toString();
}
// Cache secrets to avoid repeated API calls
let cachedApiKey = null;
async function getApiKey() {
if (cachedApiKey) return cachedApiKey;
cachedApiKey = await getSecret('api-key');
return cachedApiKey;
}
6. Error Handling
const functions = require('@google-cloud/functions-framework');
const express = require('express');
const app = express();
app.use(express.json());
// Centralized error handler
app.use((err, req, res, next) => {
console.error('Unhandled error:', err);
if (err.name === 'ValidationError') {
return res.status(400).json({ error: err.message });
}
res.status(500).json({ error: 'Internal server error' });
});
// Async error wrapper
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
app.get('/orders/:id', asyncHandler(async (req, res) => {
const order = await fetchOrder(req.params.id);
if (!order) throw new Error('Order not found');
res.json(order);
}));
functions.http('api', app);
7. CORS Handling
const functions = require('@google-cloud/functions-framework');
const express = require('express');
const cors = require('cors');
const app = express();
// Configure CORS
app.use(cors({
origin: ['https://myapp.com', 'http://localhost:3000'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
}));
app.use(express.json());
app.get('/data', (req, res) => {
res.json({ data: 'accessible from allowed origins' });
});
functions.http('api', app);
8. Deploy with gcloud CLI
# Deploy Gen 2 HTTP function
gcloud functions deploy my-api \
--gen2 \
--runtime=nodejs20 \
--region=us-central1 \
--source=. \
--entry-point=api \
--trigger-http \
--allow-unauthenticated \
--memory=512MB \
--timeout=60s \
--concurrency=80 \
--min-instances=0 \
--max-instances=100 \
--set-env-vars=NODE_ENV=production \
--set-secrets=API_KEY=api-key:latest
# Get function URL
gcloud functions describe my-api --gen2 --region=us-central1 --format='value(serviceConfig.uri)'
9. Run It Locally
The Functions Framework runs the same code on your machine: deploy only when the function behaves locally.
# Install the framework once
npm install --save-dev @google-cloud/functions-framework
# Serve the function on http://localhost:8080
npx functions-framework --target=api --port=8080
# Hit it like production would
curl -X POST http://localhost:8080/users \
-H 'Content-Type: application/json' \
-d '{"name": "Ana", "email": "ana@example.com"}'
For event-driven functions, send a CloudEvent-shaped POST; npm test with a framework like Vitest can also invoke the handler in-process without the HTTP layer.
How It Works
- Cloud Functions v2: Built on Cloud Run and Eventarc. HTTP functions are containerized and served via Cloud Run, supporting concurrency (up to 80 requests per instance by default).
- Functions framework:
@google-cloud/functions-frameworkregisters HTTP handlers viafunctions.http(). The handler can be a plain(req, res) => {}callback or a whole Express app. - Concurrency: Gen 2 functions handle up to 80 concurrent requests per instance (configurable). On Gen 1, one instance meant one request at a time. This reduces cold starts and cost.
- Secret Manager: Secrets are mounted as environment variables or accessed via the Secret Manager API. The
--set-secretsflag maps secrets to env vars at deploy time. - Scaling: Cloud Functions scales from 0 to
max-instancesbased on traffic.min-instanceskeeps instances warm to avoid cold starts (increases cost).
Production Notes
- Cold starts: expect ~1-3 s on Node.js when the service scales from zero.
min-instances=1removes them for latency-sensitive endpoints; the serverless warm pool pattern covers the scheduled-ping alternative. - Pricing: Gen 2 bills like Cloud Run: per 100 ms of vCPU/memory plus request count. The free tier covers 2M requests, 360,000 GiB-seconds and 180,000 vCPU-seconds per month; a low-traffic API usually costs $0.
- Limits: 60-minute HTTP timeout, ~32 MB max request size, read-only filesystem except
/tmp. Stream large payloads to Cloud Storage instead of buffering them. - Observability:
console.log/console.errorland in Cloud Logging automatically;gcloud functions logs read my-api --gen2 --region=us-central1tails them locally. Structured JSON entries get parsed severity and fields. - IAM:
--allow-unauthenticatedmakes the URL public; drop it for internal webhooks and grantroles/run.invokerto the caller’s service account instead.
Variants
Pub/Sub Trigger
const functions = require('@google-cloud/functions-framework');
functions.cloudEvent('processOrder', (cloudevent) => {
const pubsubMessage = cloudevent.data.message;
const data = Buffer.from(pubsubMessage.data, 'base64').toString();
const order = JSON.parse(data);
console.log('Processing order:', order.id);
processOrder(order);
});
Deploy:
gcloud functions deploy process-order \
--gen2 \
--runtime=nodejs20 \
--source=. \
--entry-point=processOrder \
--trigger-topic=orders \
--region=us-central1
Cloud Storage Trigger
const functions = require('@google-cloud/functions-framework');
functions.cloudEvent('onFileUpload', (cloudevent) => {
const bucket = cloudevent.data.bucket;
const name = cloudevent.data.name;
console.log(`File uploaded: gs://${bucket}/${name}`);
processFile(bucket, name);
});
Deploy:
gcloud functions deploy on-file-upload \
--gen2 \
--runtime=nodejs20 \
--source=. \
--entry-point=onFileUpload \
--trigger-bucket=my-upload-bucket \
--region=us-central1
Scheduled Function (Cloud Scheduler)
const functions = require('@google-cloud/functions-framework');
// Scheduler calls the function over HTTP — register an HTTP handler,
// not a cloudEvent handler
functions.http('scheduledCleanup', async (req, res) => {
console.log('Running scheduled cleanup at:', new Date().toISOString());
await cleanupExpiredRecords();
res.status(204).send();
});
gcloud functions deploy has no --schedule flag; the cron part belongs to a different service, Cloud Scheduler. Deploy the function privately, let the scheduler’s service account invoke it, then create the job:
# 1. Deploy with authentication required
gcloud functions deploy scheduled-cleanup \
--gen2 \
--runtime=nodejs20 \
--source=. \
--entry-point=scheduledCleanup \
--trigger-http \
--no-allow-unauthenticated \
--region=us-central1
# 2. Let the scheduler's service account invoke it
gcloud functions add-invoker-policy-binding scheduled-cleanup \
--gen2 \
--region=us-central1 \
--member="serviceAccount:scheduler-sa@my-project-id.iam.gserviceaccount.com"
# 3. Create the cron job (daily at 02:00 UTC)
gcloud scheduler jobs create http scheduled-cleanup-job \
--location=us-central1 \
--schedule="0 2 * * *" \
--uri="$(gcloud functions describe scheduled-cleanup --gen2 --region=us-central1 --format='value(serviceConfig.uri)')" \
--http-method=POST \
--oidc-service-account-email="scheduler-sa@my-project-id.iam.gserviceaccount.com" \
--time-zone="UTC"
Best Practices
-
For a deeper guide, see Build HTTP-Triggered Azure Functions with Python.
-
Use Gen 2: It supports concurrency, has better cold start performance, and is built on Cloud Run. Gen 1 is legacy.
-
Use Express for complex routing: For more than one endpoint, Express is cleaner than manual routing in a single function.
-
Cache secrets: Secret Manager API calls add latency. Within one instance a secret stays the same across invocations: fetch it once, keep it in memory.
-
Set concurrency: Gen 2 supports up to 80 concurrent requests. Tune it to how much memory and CPU each request actually needs.
-
Use
min-instancesfor critical APIs: warm instances cost money but the first request after idle skips the cold-start penalty. -
Separate functions by concern: Don’t put all endpoints in one function. Deploy separate functions for different API resources.
Common Mistakes
- Using Gen 1: Gen 1 doesn’t support concurrency and has slower cold starts. Always use
--gen2. - Not handling CORS: Browser requests from different origins will fail. Use the
corsmiddleware with explicit allowed origins. - Blocking the event loop: Synchronous CPU-heavy operations block all concurrent requests. Use async operations or offload to Cloud Tasks.
- Hardcoding secrets: API keys in source code end up in git history forever. Use Secret Manager or environment variables set via
--set-secrets. - Ignoring timeout: Default timeout is 60 seconds. Long-running operations need a higher timeout or should be offloaded to Cloud Tasks.
- Forgetting
awaiton async calls:const user = getUserFromDb(id)returns a Promise, not a user;res.json(user)sends{}andif (!user)never triggers. Handlers must beasyncandawaitevery async call. - Scheduling with a flag that doesn’t exist:
gcloud functions deploy --schedulefails: scheduling lives in Cloud Scheduler, which needs its own job plus an invoker binding on the function.
Further Reading
- Cloud Functions documentation — triggers, runtimes and limits
- Functions Framework for Node.js — the library behind
functions.http() - Schedule jobs with Cloud Scheduler — cron syntax and OIDC invocation
- Cloud Run pricing — what Gen 2 functions actually cost
Frequently Asked Questions
Cloud Functions vs Cloud Run — which should I use?
Cloud Functions is simpler for event-driven workloads (HTTP, Pub/Sub, Storage triggers). Cloud Run is better for containerized applications, custom runtimes, and long-running processes. Cloud Functions v2 is actually built on Cloud Run.
What is the maximum timeout for Cloud Functions?
Gen 2: 60 minutes (default 60 seconds). For longer tasks, use Cloud Run jobs or Cloud Workflows.
Can I use TypeScript with Cloud Functions?
Yes. Use tsconfig.json and compile to JavaScript before deploying, or use a build step in Cloud Build. The --source flag can point to a build directory.
How do I handle long-running tasks?
For tasks longer than the timeout, return immediately and offload to Cloud Tasks or Pub/Sub. The function can publish a message, and another function processes it asynchronously.
How does concurrency work in Gen 2?
Each instance handles up to 80 requests simultaneously by default. This means shared state must be thread-safe. Use connection pooling for databases: one pool per instance, shared across concurrent requests.
Why does my function return an empty object instead of data?
Usually a missing await: an async helper returns a Promise, and res.json() serializes it to {}. Mark the route handler async and await the call.
Related Resources
Package Python Dependencies for AWS Lambda with Layers
Package Python dependencies for AWS Lambda using Lambda Layers, Docker builds for native extensions, and SAM/Serverless Framework integration.
RecipeHTTP-Triggered Azure Functions in Python
Create HTTP-triggered Azure Functions in Python with binding configuration, async handlers, dependency injection, and deployment via Azure CLI.
GuideComplete Guide to Serverless Architecture
Decide when to go serverless and when not to. FaaS patterns, cold starts, cost models, vendor lock-in, and migration strategies for production.
RecipeReduce AWS Lambda Cold Start with Provisioned Concurrency
Minimize Lambda cold start latency using provisioned concurrency, ARM64 Graviton, lighter dependencies, and initialization code optimization.
PatternServerless Warm Pool Pattern
Keep Lambda functions warm by sending periodic ping events to reduce cold start latency for latency-sensitive workloads.
RecipeSecure API Gateway with Custom Lambda Authorizers
Implement custom Lambda authorizers for API Gateway with JWT validation, IAM policy generation, and caching for token-based authentication in serverless APIs.