Edge Developer Platform
  • Pages
    • Product Introduction
    • Quick Start
      • Importing a Git Repository
      • Starting From a Template
      • Direct Upload
    • Framework Guide
    • Project Guide
      • Project Management
      • edgeone.json
      • Configuring Cache
      • Error Codes
    • Build Guide
    • Deployment Guide
      • Overview
      • Create Deploys
      • Manage Deploys
      • Deploy Button
      • Use Github Actions
      • Using CNB Plug-In
      • Using IDE Plug-In
    • Domain Management
      • Overview
      • Custom Domain
      • Configuring an HTTPS Certificate
      • How to Configure a DNS CNAME Record
    • Pages Functions
    • KV Storage
    • Edge AI
    • API Token
    • EdgeOne CLI
    • Pages MCP
    • Integration Guide
      • AI
        • Dialogue Large Models Integration
        • Images Large Models Integration
      • Database
        • Supabase Integration
        • Pages KV Integration
      • Ecommerce
        • Shopify Integration
        • WooCommerce Integration
      • Payment
        • Stripe Integration
        • Integrating Paddle
      • CMS
        • WordPress Integration
        • Contentful Integration
        • Sanity Integration
      • Authentication
        • Supabase Integration
        • Clerk Integration
    • Best Practices
      • Using General Large Model to Quickly Build AI Application
      • Using Edge AI Model to Quickly Build AI Site
      • Building an Ecommerce Platform with WordPress + WooCommerce and GatsbyJS
      • Building a SaaS Site Using Supabase and Stripe
      • Building a Company Brand Site Quickly
      • How to Quickly Build a Blog Site
    • Migration Guides
      • Migrating from Vercel to EdgeOne Pages
      • Migrating from Cloudflare Pages to EdgeOne Pages
      • Migrating from Netlify to EdgeOne Pages
    • Troubleshooting
    • FAQs
    • Contact Us
    • Release Notes

Pages Functions

Overview

Pages edge functions provide a Serverless code execution environment on EdgeOne edge nodes. You just need to write business function code and set trigger rules, without the need to configure and manage server infrastructure, to run code securely and with elastic scaling on edge nodes close to users.






Advantages of Edge Functions

Distributed deployment
EdgeOne has over 3,200 edge nodes, and edge functions run on edge nodes via distributed deployment.

Ultra-low latency
Client requests will be automatically scheduled to the edge node closest to your users. When a trigger rule is hit, the edge function processes the request and returns the response result to the client, significantly reducing access latency.

Elastic Scale-out
Edge functions can route client requests from closest to farthest based on a sudden increase in request volume, processing them on edge nodes with sufficient computational resources. You have no need to worry when spikes occur.

Serverless Architecture
You no longer need to care about or maintain the memory, CPU, network, and other infrastructure resources of the underlying server, freeing up effort to focus on business code development.


Quick Start Guide

1. Install the npm package: npm install -g edgeone. For more commands, see the scaffolding document.
2. Local development: Under the Pages code project
2.1 Function initialization: edgeone pages init, automatically initializes the functions directory to handle functions code.
2.2 Associate project: edgeone pages link, fill in the current project name, automatically associate project KV configuration, environment variables, etc.
2.3 Local development: edgeone pages dev, start up the local proxy service to perform function debugging
3. Function release: Push code to the remote repository for auto-building and function release.



Routing

Pages Functions generates access routes based on the /functions directory structure. You can create subdirectories at any level under the /functions directory in your project repository. See 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 file structure in the above directory will generate the following routes after platform construction by EdgeOne Pages. These routes map Pages URLs to the /functions file. When a client accesses the URL, it will trigger the corresponding file code to run:
File path
Routing
/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/...
Note:
- The trailing slash / in routing 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 resource of Pages.
- Routing is 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, the single-level dynamic path is `/functions/api/users/[id].js`, and the multi-level dynamic path is `/functions/api/[[default]].js`. See the following usage:
File path
Routing
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 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 these properties:
request: client request object
params: dynamic routing /functions/api/users/[id].js parameter value
export function onRequestGet(context) {
return new Response(`User id is ${context.params.id}`);
}
env: Pages environment variables
waitUntil: (task: Promise<any>): void; Used to notify the edge function to wait for the promise completion, extending the event handling lifecycle.


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 found in edge function usage. See the description below:
API
Description
Cache is designed based on the Web APIs standard Cache API. The Functions runtime environment will inject a global Cache object, which provides a group of Cache operation interfaces.
Cookies provide a group of cookie operation APIs.
Designed based on the Web APIs standard TextEncoder and TextDecoder, it implements an encoder and decoder.
Designed based on the Web APIs standard Fetch API. The function runtime can use fetch to initiate async requests and retrieve remote resources.
Headers are designed based on the Web APIs standard Headers. Applicable to HTTP request and response header operations.
Request represents the HTTP request object, designed based on the Web APIs standard Request.
Response represents the HTTP response, designed based on the Web APIs standard Response.
ReadableStream, also known as readable stream, 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 group of common encryption APIs. Compared with pure JavaScript implementation, Web Crypto API delivers higher performance.
Edge Function is a Serverless code execution environment designed and implemented based on the V8 JavaScript engine. It provides the following standardized Web APIs.
Note:
Currently, Edgeone CLI does not support using fetch to access Edgeone node cache or origin in the debugging environment.
Use context.request.eo to get the client's GEO info.
Pages Functions cannot be used with addEventListener. Listen to client requests based on Function Handlers.


Sample Function


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 detailed information on how to use KV storage, see KV storage.
export async function onRequest({ request, params, env }) {
// my_kv is the variable name when you bind a namespace in the 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': '*',
},
});
}