Node.js
Overview
The Node.js runtime environment supports JavaScript and TypeScript development, can use the massive modules in the npm ecosystem directly, and is suitable for building API services and full-stack Web applications.
Strengths
Rich Node.js ecosystem: You can directly use various third-party libraries and tools from npm, easily integrate services like databases, AI, and payment, 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.
Development Mode
Node.js functions support various development modes:
Mode | Scenarios | Routing Mode | Framework Dependency |
Handler mode | Simple API, Serverless style | File system route (file as route) | None (pure native) |
Framework mode | Complete Web application, RESTful API | Built-in framework route | Express, Koa |
Quick Start
Create hello.js under the ./cloud-functions/api directory of your project and use the following example code to create your first Node.js function:
// ./cloud-functions/api/hello.jsexport default function onRequest(context) {return new Response('Hello from Node.js!');}
We recommend that you manage function files through subdirectories. In the following example, create nodeinfo.js under ./cloud-functions/api for returning information related to node.
// ./cloud-functions/api/nodeinfo.jsimport * 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 using Express/Koa to develop in a Node.js function, note that framework routes only need to be centralized in a function file for processing, without the need to start up an HTTP Server, and the instance of the framework must be exported. In the following example, create [[default]].js under ./cloud-functions/express for processing express business logic:
// ./cloud-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();});app.get("/", (req, res) => {res.json({ message: "Hello from Express on Node.js!" });});app.get("/users/:id", (req, res) => {const { id } = req.params;res.json({ userId: id, message: `Fetched user ${id}` });});// Export the express instanceexport default app;
Routing
Node.js functions generate access routes based on the
/cloud-functions directory structure. You may create subdirectories at any level under the /cloud-functions directory in the project repository. See the following example....cloud-functions├── index.js├── hello-pages.js├── helloworld.js├── api├── users├── list.js├── geo.js├── [id].js├── visit├── index.js├── [[default]].js...
The above directory file structure will generate the following routes after EdgeOne Pages platform construction. These routes are mapped to the
/cloud-functions file. When client access the URL, it will trigger the corresponding file code to run:File path | Routing |
/cloud-functions/index.js | example.com/ |
/cloud-functions/hello-pages.js | example.com/hello-pages |
/cloud-functions/helloworld.js | example.com/helloworld |
/cloud-functions/api/users/list.js | example.com/api/users/list |
/cloud-functions/api/users/geo.js | example.com/api/users/geo |
/cloud-functions/api/users/[id].js | example.com/api/users/1024 |
/cloud-functions/api/visit/index.js | example.com/api/visit |
/cloud-functions/api/[[default]].js | example.com/api/books/list,example.com/api/books/1024,example.com/api/... |
Note:
The trailing slash in routes is optional.
/hello-pages and /hello-pages/ will be routed to /cloud-functions/hello-pages.js.If a Node.js route conflicts with a static resource route, client requests will be preferentially routed to the static resource.
Routes are case-sensitive. /helloworld will be routed to /cloud-functions/helloworld.js and cannot be routed to /cloud-functions/HelloWorld.js.
Route Match Priority
Routes are matched based on the following priorities (from high to low):
1. Static route: Paths with exact matching take priority (for example,
/api/users/list).2. Single-level dynamic routing:
[param] matches one path segment (for example, /api/users/[id])3. Multi-level dynamic routing (Catch-all):
[[param]] matches one or more path segments (for example, /api/[[default]])In routes of the same level, longer (more specific) paths have higher priority.
Entry File Identification
Not all
.js/.ts files are registered as routes. Only files that export Function Handlers methods (such as onRequest, onRequestGet) or framework instances (such as Express app) are generated as routes..js / .ts files excluding entry flag will be deemed as auxiliary modules, will be copied to build artifacts for other entry points to refer, but will not register as standalone route.
Dynamic Routing
Node.js function support dynamic routing. The above example shows a first-level dynamic path /cloud-functions/api/users/[id].js and a multi-level dynamic path /cloud-functions/api/[[default]].js. See the following usage for reference:
File path | Routing | match |
/cloud-functions/api/users/[id].js | example.com/api/users/1024 | Yes |
| example.com/api/users/vip/1024 | No |
| example.com/api/vip/1024 | No |
/cloud-functions/api/[[default]].js | example.com/api/books/list | Yes |
| example.com/api/1024 | Yes |
| example.com/v2/vip/1024 | No |
Dynamic Routing Parameter Retrieval
In Handler mode, you can get dynamic routing parameters via
context.params:// ./cloud-functions/api/users/[id].jsexport function onRequestGet(context) {return new Response(`User id is ${context.params.id}`);}
Built-in Route 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 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 cloud-functions/express/*, use [[default]].js as the entry, and all Express-related routing is inside [[default]].js:
cloud-functions└── express└── [[default]].js # express.js/koa.js entry point with built-in route definition
Function Handlers
Use Functions Handlers to 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) |
Basic Usage
The Handler function processes ALL HTTP requests by exporting the
onRequest method:// ./cloud-functions/api/hello.jsexport default function onRequest(context) {return new Response('Hello, world!', {headers: { 'Content-Type': 'text/plain' },});}
Handling Multiple Request Methods
By exporting different Handler methods, you can process different types of HTTP requests:
// ./cloud-functions/api/users/index.jsexport function onRequestGet(context) {return new Response(JSON.stringify({ users: [] }), {headers: { 'Content-Type': 'application/json' },});}export function onRequestPost(context) {return context.request.json().then(data => {return new Response(JSON.stringify({ message: 'Created', data }), {status: 201,headers: { 'Content-Type': 'application/json' },});});}export function onRequestDelete(context) {return new Response(null, { status: 204 });}
Retrieve Query Parameters
// ./cloud-functions/api/search.jsexport function onRequestGet(context) {const url = new URL(context.request.url);const name = url.searchParams.get('name') || 'Guest';return new Response(JSON.stringify({ hello: name }), {headers: { 'Content-Type': 'application/json' },});}
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
/cloud-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.
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/
