0
0
GcpHow-ToBeginner · 4 min read

How to Use Cloud Function with Node.js on Google Cloud

To use a Cloud Function with Node.js, write your function code in JavaScript, export it, and deploy it on Google Cloud using the gcloud CLI. The function runs in response to events like HTTP requests or cloud storage changes.
📐

Syntax

A Cloud Function in Node.js is a JavaScript function exported from a file, usually index.js. It receives request and response objects for HTTP triggers or event and context for background triggers.

Use exports.functionName = (req, res) => { ... } for HTTP functions.

javascript
exports.helloWorld = (req, res) => {
  res.send('Hello, World!');
};
💻

Example

This example shows a simple HTTP Cloud Function that responds with a greeting message. Deploying this function lets you call it via a URL.

javascript
exports.greetUser = (req, res) => {
  const name = req.query.name || 'Guest';
  res.send(`Hello, ${name}! Welcome to Cloud Functions.`);
};
Output
If you call the function URL with ?name=Anna, it responds: Hello, Anna! Welcome to Cloud Functions.
⚠️

Common Pitfalls

  • Not exporting the function properly: The function must be exported using exports.functionName.
  • For HTTP functions, forgetting to send a response causes timeout errors.
  • Using synchronous code without callbacks or promises can block the function.
  • Deploying without specifying the correct trigger type (HTTP vs background) leads to errors.
javascript
/* Wrong: function not exported */
function myFunc(req, res) {
  res.send('Hi');
}

/* Right: exported function */
exports.myFunc = (req, res) => {
  res.send('Hi');
};
📊

Quick Reference

StepDescription
Write function in index.jsExport your function using exports.name = (req, res) => {...}
Deploy with gcloud CLIUse: gcloud functions deploy FUNCTION_NAME --runtime nodejs18 --trigger-http --allow-unauthenticated
Test functionCall the function URL in a browser or with curl
Check logsUse gcloud functions logs read FUNCTION_NAME to debug

Key Takeaways

Export your Node.js function properly using exports.functionName syntax.
Use HTTP triggers for web requests and always send a response to avoid timeouts.
Deploy functions with the correct runtime and trigger using the gcloud CLI.
Test your function by calling its URL and check logs for errors.
Avoid blocking code; use async patterns if needed.