Node Functions
Overview
Node Functions simplifies backend development and seamlessly integrates with front-end projects in a Node.js runtime. It supports traditional HTTP requests and real-time two-way communication through the WebSocket protocol. You can build and deploy dynamic APIs and complex business logic in a uniform project. The platform handles version control, build and deploy automatically, intelligently scales based on business workload, and helps you launch quickly with continuous delivery.
Strengths
Rich Node.js ecosystem: can directly access the massive modules in the npm ecosystem, easily integrate various third-party libraries and tools, and meet complex business needs.
Full stack development experience: No need to separate frontend and backend projects. Develop and deploy in one project to drastically enhance collaboration efficiency.
Route as a service: Define API routes through the file system to implement rapid development and deployment of backend logic, managing backend services as conveniently as frontend pages.
Supports real-time communication: Built-in support for the WebSocket protocol facilitates the construction of modern Web applications requiring persistent connections, such as real-time chat and data push.
Quick Start
Create hello.js in the ./node-functions/api directory and use the following example code to create your first Node Functions:
// File path ./node-functions/api/hello.js// Access path example.com/api/helloexport default function onRequest(context) {return new Response('Hello from Node Functions!');}
Note:
Create index.js in the ./node-functions directory. Accessing the root path will enter the function instead of the homepage.
Create [[id]].js under the ./node-functions directory. All paths except the root path will enter the function, which must handle the return of static resources.
We recommend that you manage function files through subdirectories. In the following example, create nodeinfo.js under ./node-functions/api to return information related to node:
// File path ./node-functions/api/nodeinfo.js// Access path example.com/api/nodeinfoimport * as os from 'node:os'import { randomUUID, createHash } from 'node:crypto'export const onRequestGet = async ({ request }) => {const info = {nodeVersion: process.version,pid: process.pid,platform: os.platform(),url: request.url,}return new Response(JSON.stringify(info), {status: 200,headers: { 'Content-Type': 'application/json; charset=UTF-8' },})}
When developing with Express/Koa in Node Functions, the framework's routes only need to be centralized in a function file for processing, without the need to start an additional HTTP Server, and the instance of the framework must be exported. In the following example, create [[default]].js under ./node-functions/express to handle the business logic of Express:
// File path ./node-functions/express/[[default]].jsimport express from "express";const app = express();// Add log middlewareapp.use((req, res, next) => {console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);next();});// Add root route handling, access path example.com/express/app.get("/", (req, res) => {res.json({ message: "Hello from Express on Node Functions!" });});// Access path example.com/express/users/123app.get("/users/:id", (req, res) => {const { id } = req.params;res.json({ userId: id, message: `Fetched user ${id}` });});// Export the express instanceexport default app;
Function Debugging
1. Install EdgeOne CLI:
npm install -g edgeone2. Local development: Execute
edgeone pages dev in your Pages code project to start local service and perform function debugging.3. Function release: Push code to remote repository for auto-build function release.
Routing
Node Functions generates access routes based on the
/node-functions directory structure. You can create subdirectories at any level under the /node-functions directory in the project repository. See the example below....node-functions├── index.js├── hello-pages.js├── helloworld.js├── api├── users├── list.js├── geo.js├── [id].js├── visit├── index.js├── [[default]].js...
The file structure in the above directory will generate the following routes after platform construction by EdgeOne Pages. These routes map Pages URLs to
/node-functions files. When a client accesses the URL, it will trigger the corresponding file code to run:File path | Routing |
/node-functions/index.js | example.com/ |
/node-functions/hello-pages.js | example.com/hello-pages |
/node-functions/helloworld.js | example.com/helloworld |
/node-functions/api/users/list.js | example.com/api/users/list |
/node-functions/api/users/geo.js | example.com/api/users/geo |
/node-functions/api/users/[id].js | example.com/api/users/1024 |
/node-functions/api/visit/index.js | example.com/api/visit |
/node-functions/api/[[default]].js | example.com/api/books/list example.com/api/books/1024 example.com/api/... |
Note:
The trailing slash / is selectable.
/hello-pages and /hello-pages/ will be routed to /node-functions/hello-pages.js.If no Node Functions route is matched, client requests will be routed to the corresponding static resource of Pages.
Route is case-sensitive. /helloworld will be routed to /node-functions/helloworld.js, and cannot be routed to /node-functions/HelloWorld.js.
Dynamic Routing
Node Functions support dynamic routing. In the above example, the first-level dynamic path is /node-functions/api/users/[id].js, and the multi-level dynamic path is /node-functions/api/[[default]].js. See the following usage:
File path | Routing | Match |
/node-functions/api/users/[id].js | example.com/api/users/1024 | Yes |
| example.com/api/users/vip/1024 | No |
| example.com/api/vip/1024 | No |
/node-functions/api/[[default]].js | example.com/api/books/list | Yes |
| example.com/api/1024 | Yes |
| example.com/v2/vip/1024 | No |
Built-in Routing Framework
When developing with the Express/Koa framework, there are key points to pay attention to in code compilation and file group organization.
Express/Koa framework:
All routing services are consolidated in one function file, and the file name must be in [[]] format, such as [[default]].js.
No need to start up an additional HTTP Server or set port listen
The framework instance must be exported, otherwise the builder will not recognize it as a function
export default app;For example, to create an Express app in the directory node-functions/express/*, use [[default]].js as the entry, and all Express-related routing is inside [[default]].js:
node-functions└── express└── [[default]].js # express.js/koa.js entry point with built-in route definition
Function Handlers
Functions Handlers can create custom request handlers for Pages and define RESTful APIs to implement full-stack applications. Supported handler methods:
Handlers method | Description |
onRequest(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( GET, POST, PATCH, PUT, DELETE, HEAD, OPTIONS) |
onRequestGet(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( GET) |
onRequestPost(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( POST) |
onRequestPatch(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( PATCH) |
onRequestPut(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( PUT) |
onRequestDelete(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( DELETE) |
onRequestHead(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( HEAD) |
onRequestOptions(context: EventContext): Response | Promise<Response> | Match HTTP Methods ( OPTIONS) |
EventContext object description
The context is an object passed to Function Handlers methods, containing the following properties:
uuid: EO-LOG-UUID represents the unique identifier of an EO request
params: dynamic routing
/node-functions/api/users/[id].js parameter valueexport function onRequestGet(context) {return new Response(`User id is ${context.params.id}`);}
env: Pages environment variables
clientIp: client IP address
server:
region: region code of the deployment location
requestrequestId: request ID, used for log tracking>
geo: client geographic location
Response object description
The function must return a Response object to respond to the client's HTTP request, including headers, status, and body.
Handling WebSocket Requests
In addition to standard HTTP requests, Node Functions also support processing and responding to WebSocket upgrade requests to create a persistent bidirectional communication connection.
When the function receives an HTTP GET request with the Upgrade: websocket header, you can upgrade the connection to WebSocket through the platform. After upgrade, you can listen and send messages on the server. Refer to Pages' AI Voice Chat Template to learn how to achieve a real-time voice AI conversation service.
Use Limits
Content | Limit | Description |
Code package size | 128 MB | Single function code package size supports up to 128 MB |
Request body size | 6 MB | Client request body supports up to 6 MB |
Running time | 30s | Wall time |
Development Language | Node | Currently only support Node.js, default version v20.x |
Note:
When file transfer is involved, storing data that requires long-term retention is not recommended. We recommend using Tencent Cloud COS to handle persistence needs.
Log Analysis
The Pages console provides basic log viewing functionality. Developers can view basic log information for Node Functions calls, quickly detect and resolve anomalies or errors in API calls through logs. For detailed directions, view the document Log Analysis.
Example Template
Connect to a third-party MySQL database:
Preview address: https://mysql-template.edgeone.app
Source code address: https://github.com/TencentEdgeOne/mysql-template/
Use the Express framework:
Preview address: https://express-template.edgeone.app
Source code address: https://github.com/TencentEdgeOne/express-template/
Use the Koa framework:
Preview address: https://koa-template.edgeone.app
Source code address: https://github.com/TencentEdgeOne/koa-template/
AI Voice Conversation (WebSocket Application):
Preview address: https://pages-ai-voice-chat.edgeone.app
Source code address: https://github.com/TencentEdgeOne/pages-ai-voice-chat
