Edge Developer Platform
  • Pages
    • Product Introduction
    • Quick Start
    • Framework Guide
    • Project Guide
      • Project Management
      • edgeone.json
      • Error Codes
    • Build Guide
    • Deployment Guide
    • Domain Management
    • Pages Functions
    • KV Storage
    • EdgeOne CLI
    • FAQs
    • Contact Us
    • Release Notes
    • Migration Guides
      • Migrating from Vercel to EdgeOne Pages
      • Migrating from Cloudflare Pages to EdgeOne Pages
      • Migrating from Netlify to EdgeOne Pages
このページは現在英語版のみで提供されており、日本語版も近日中に提供される予定です。ご利用いただきありがとうございます。

Pages Functions

Overview

Pages Edge Functions provide the Serverless code execution environment of EdgeOne edge nodes. You only need to write business function code and set trigger rules, without the need for configuring and managing server infrastructure, to run code elastically and securely on edge nodes close to users.






Advantages of Edge Functions

Distributed Deployment
EdgeOne supports more than 3,200 edge nodes. Edge Functions is deployed on edge nodes in distributed mode.

Ultra-low latency
Client requests are automatically scheduled to the edge nodes that are closest to users. If triggering rules are hit, edge functions are triggered to process the requests and return results to the client. This helps significantly reduce the client access latency.

Elastic Scale-out
Edge Functions schedules requests to edge nodes that are allocated sufficient computing resources based on the proximity of the user when spikes occur in client requests.

Serverless Architecture
You no longer need to worry about and maintain underlying server resources such as memory, CPU, network, and other infrastructure resources. This frees up your energy to focus more on business code development.


Getting Started

1. Install npm package:npm install -g edgeone, for more commands see the scaffolding documentation
2. Local Development: under the Pages code project
2.1 Function initialization: edgeone pages init, automatically initializes the functions directory to host functions code
2.2 Link project:edgeone pages link, enter the current project name to automatically link the project's KV configuration, environment variables, and other information
2.3 Local development: edgeone pages dev, starts the local proxy service for function debugging
3. Function Deployment: push the code to a remote repository to automatically build and deploy the function



Route

Pages Functions generate access routing based on the /functions directory structure. You can create subdirectories of any level under the /functions directory in your project repository, as shown in the example below.
...
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 being built by the EdgeOne Pages platform. These routes map the Pages URL to the /functions file, and when the client accesses the URL, the corresponding file code will be triggered to run:
File path
Route
/functions/index.js
example.com/
/functions/hello-pages.js
example.com/hello-pages
/functions/HelloWorld.js
example.com/HelloWorld
/functions/api/users/list.js
example.com/api/users/list
/functions/api/users/geo.js
example.com/api/users/geo
/functions/api/users/[id].js
example.com/api/users/1024
/functions/api/visit/index.js
example.com/api/visit
/functions/api/[[default]].js
example.com/api/books/list
example.com/api/books/1024
example.com/api/...
Notes:
The trailing slash / in the route is optional. /hello-pages and /hello-pages/ will be routed to /functions/hello-pages.js.
If no Pages Functions route is matched, client requests will be routed to the corresponding static assets of Pages.
Routes are case-sensitive. /HelloWorld will be routed to /functions/HelloWorld.js and cannot be routed to /functions/helloworld.js.

Dynamic routing
Pages Functions support dynamic routing. In the above example, a single-level dynamic path is /functions/api/users/[id].js, and a multi-level dynamic path is /functions/api/[[default]].js. Refer to the usage below:
File path
Route
Match
/functions/api/users/[id].js
example.com/api/users/1024
Yes
example.com/api/users/vip/1024
No
example.com/api/vip/1024
No
/functions/api/[[default]].js
example.com/api/books/list
Yes
example.com/api/1024
Yes
example.com/v2/vip/1024
No


Function Handlers

Using Functions Handlers, you can create custom request handlers for Pages and define RESTful APIs to implement full-stack applications. The following Handlers methods are supported:
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
context is the object passed to Function Handlers methods, containing the following attributes:
request: client request object
params: dynamic routing /functions/api/users/[id].js parameter values
export function onRequestGet(context) {
return new Response(`User id is ${context.params.id}`);
}
env: Pages environment variables


Runtime APIs

Pages Functions are implemented based on Edge Functions, providing a Serverless code execution environment on EdgeOne edge nodes. They support ES6 syntax and standard Web Service Worker API. Most Runtime APIs can be referenced from the Edge Functions usage, as described below:
API
Description
Cache is designed based on the Web APIs standard Cache API. During the Functions runtime, a global caches object is injected, which provides a set of cache operation APIs.
Cookies provide a set of cookie operation APIs.
Designed based on the Web APIs standards TextEncoder and TextDecoder, implementing encoders and decoders.
Designed based on the Web APIs standard Fetch API. During the runtime of edge functions, fetch can be used to initiate asynchronous requests to fetch remote resources.
Headers are designed based on the Web APIs standard Headers. They can be used for HTTP request and response header operations.
Request represents an HTTP request object, designed based on the Web APIs standard Request.
Response represents an HTTP response, designed based on the Web APIs standard Response.
ReadableStream, also known as the readable end, is designed based on the Web APIs standard ReadableStream.
Web Crypto API is designed based on the Web APIs standard Web Crypto API. It provides a set of common cryptographic operation interfaces, offering higher performance compared to cryptographic interfaces implemented purely in JavaScript.
Edge Functions designs a serverless code execution environment based on the V8 JavaScript engine and provides the following standardized Web APIs.
Notes:
Currently, the Edgeone CLI debugging environment does not support using fetch to access EdgeOne node cache or origin.
Use context.request.eo to obtain client GEO information.
Pages Functions do not support using addEventListener, please listen to client requests based on Function Handlers.


Sample Functions


Retrieve User Access Geolocation:
export function onRequest({request}) {
const geo = request.eo.geo;
const res = JSON.stringify({
geo: geo,
});

return new Response(res, {
headers: {
'content-type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
});
}


Use KV to Record Page Views:
For more details on how to use Key-Value Storage, refer to Key-Value Storage.
export async function onRequest({ request, params, env }) {
// my_kv is the variable name you bind to the namespace in your project
const visitCount = await my_kv.get('visitCount');
let visitCountInt = Number(visitCount);
visitCountInt += 1;
await my_kv.put('visitCount', visitCountInt.toString());

const res = JSON.stringify({
visitCount: visitCountInt,
});

return new Response(res, {
headers: {
'content-type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
});
}




Connect to Supabase Third-Party Database:
import { createClient } from '@supabase/supabase-js';

export async function onRequest({ request, params, env }) {
const supabase = createClient(env.supabaseUrl, env.supabaseKey);

let { data } = await supabase.from('users').select('*');

return new Response(JSON.stringify({
users: data,
}), {
headers: {
'content-type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
});
}