Skip to main content

Node.js Quick Start

This document describes how to create a Node.js application from scratch and deploy it to a CloudBase HTTP cloud function.

Prerequisites

Before you begin, ensure that you have:

  • Installed Node.js (v18 or later is recommended)
  • Have a Tencent Cloud account and have activated the CloudBase service
  • Have a basic knowledge of Node.js development

Step 1: Create the project directory

Create a new directory named helloworld and enter the directory:

mkdir helloworld
cd helloworld

Step 2: Initialize Project Configuration

Create a package.json file to describe project information and dependencies. You can quickly initialize the project configuration by running npm init -y.

{
"name": "helloworld",
"description": "Simple hello world sample in Node",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Tencent CloudBase",
"license": "Apache-2.0"
}

Step 3: Write the Application Code

Create an index.js file in the same directory, which is the entry file of the application:

⚠️ Important: CloudBase HTTP cloud functions must use the default port 9000.

import { createServer } from "node:http";
import { Readable } from "node:stream";

const server = createServer(async (req, res) => {
if (req.ur.split('?')[0] === "/") {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end("Hello World!");
} else if (req.ur.split('?')[0] === "/myip") {
// Set CORS headers to allow cross-origin requests
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Content-Type", "application/json");

try {
// Use fetch to obtain remote data (using ipinfo.io as an example here)
const response = await fetch("https://ipinfo.io", {
headers: {
Accept: "application/json",
},
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

Readable.fromWeb(response.body).pipe(res);
} catch (error) {
console.error("Failed to obtain IP information:", error);
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({
error: "Failed to fetch remote data",
message: error.message
}));
}
} else if (req.ur.split('?')[0] === "/health") {
// Health Check Endpoint
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
status: "healthy",
timestamp: new Date().toISOString(),
version: "1.0.0"
}));
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Not Found" }));
}
});

const port = 9000;
const host = "0.0.0.0";
server.listen(port, host, () => {
console.log(`Server running at http://localhost:${port}/`);
console.log(`Try accessing http://localhost:${port}/myip to see your IP info`);
console.log(`Health check available at http://localhost:${port}/health`);
});

This code creates a basic Web server that provides the following features:

  • Root path (/): returns "Hello World!" message
  • IP Query (/myip): obtains and returns the client's IP information
  • Health Check (/health): returns service status information
  • Error Handling: returns 404 error for unknown paths
Tip

In addition to using the native Node.js http module, you can also use the @cloudbase/functions-framework for a more streamlined development experience. For more details, see Functions Framework Quick Start.

Step 4: Create the Startup Script

💡 Note:

  • When creating the scf_bootstrap file on windows, it is recommended to use
  • When creating the scf_bootstrap file using vscode on windows, deploying to an HTTP cloud function may result in an error: scf_bootstrap file does not exist
  • This error occurs because the script file contains Windows-style carriage returns (^M), causing Linux to fail to recognize the interpreter path correctly. This is a common issue in WSL

Create the scf_bootstrap file (with no file extension), which is the startup script for CloudBase cloud functions:

#!/bin/bash
node index.js

⚠️ Note:

  • The file name must be scf_bootstrap with no extension
  • Ensure the file has execute permissions

Grant execute permissions to the startup script:

chmod +x scf_bootstrap

Step 5: Local Testing (Optional)

Before deployment, you can test the application locally:

node index.js

After successful testing, you can verify in the following ways:

  • Access http://localhost:9000/ to view the Hello World message
  • Access http://localhost:9000/myip to view the IP information
  • Access http://localhost:9000/health to view the health status

Press Ctrl + C to stop the local server.

Step 6: Deploy to CloudBase HTTP cloud function

Prepare Deployment Files

Ensure your project directory contains the following files:

helloworld/
|-- scf_bootstrap
├── package.json
└── index.js

Deploy via the console

  1. Log in to TCB/cloud function
  2. Click "New Cloud Function"
  3. Select "HTTP cloud function"
  4. Fill in the function name (such as: helloworld)
  5. Select runtime: Node.js 18.x
  6. Select the "Local upload" method
  7. Package the project files into a zip file and upload it (Please select the files to package, not the root directory folder)
  8. Click "OK" to complete the deployment

Deploy via CLI

For details, see Deploy HTTP function via CLI

Package the project

If you need to package manually, you can use the following command:

# Create zip package
zip -r helloworld.zip package.json index.js scf_bootstrap

Step 7: Access Your Application

After successful deployment, you can refer to Accessing Cloud Functions via HTTP to set up custom domain access to the

You can test in the following ways:

  • Access the root path to view the Hello World message
  • Access the /myip path to view the IP information
  • Access the /health path to check the service status

Frequently Asked Questions

Q: Why must port 9000 be used?

A: CloudBase HTTP cloud functions require the application to listen on port 9000, which is the standard configuration of the platform.

Q: How to view function logs?

A: On the Cloud Functions page of the CloudBase console, click the function name to go to the details page, where you can view the runtime logs.

Q: Which Node.js versions are supported?

A: CloudBase supports Node.js 12.x, 14.x, 16.x, 18.x and other versions. It is recommended to use the latest LTS version.

Q: How to handle CORS cross-origin issues?

A: Set CORS-related headers such as Access-Control-Allow-Origin in the response headers, as shown in the example code.

Q: How to handle long function cold startup times?

A: You can reduce cold startup time by implementing a warm-up mechanism, reducing the size of dependency packages, optimizing code logic, and other methods.

Best Practices

  1. Error Handling: Always add proper error handling for asynchronous operations.
  2. Response Header Settings: Correctly set the Content-Type and other necessary response headers.
  3. Logging: Use console.log to record key information for debugging purposes.
  4. Environment Variables: Use process.env to manage configuration information.
  5. Code Structure: For complex applications, it is recommended to use frameworks such as Express.js.

Next steps