Edge Developer Platform
  • Edge Functions
    • Overview
    • Getting Started
    • Operation Guide
      • Function Management
      • Web Debugging
      • Function Trigger
      • Environment Variable
      • Code Replica
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • Sample Functions
      • Example Overview
      • Obtaining Client URL Information
      • Customization Based on Client Geo Location
      • Obtaining Client Geo Location Information
      • Batch Redirect
      • URL rewrite based on regular expressions
      • Returning an HTML Page
      • Returning a JSON Object
      • Fetch Remote Resources
      • Authenticating a Request Header
      • Modifying a Response Header
      • Performing an A/B Test
      • Setting Cookies
      • Performing Redirect Based on the Request Location
      • Using the Cache API
      • Caching POST Requests
      • Responding in Streaming Mode
      • Merging Resources and Responding in Streaming Mode
      • Protecting Data from Tampering
      • Rewriting a m3u8 File and Configuring Authentication
      • Adaptive Image Resize
      • Image Adaptive WebP
      • Customize Referer restriction rules
      • Remote Authentication
      • HMAC Digital Signature
      • Naming a Downloaded File
      • Obtaining Client IP Address
      • Complex origin-pull URL rewriting
      • Web Bot Auth
    • Practical Tutorial
      • Overview
      • Origin retrieval based on user IP/geographic location
        • EdgeOne Implementation of Session Persistence Based on Client IP Addresses
        • EdgeOne Implementation of Origin-Pull Based on Client's Geo Location
      • APK dynamic packaging
        • EdgeOne enables dynamic packaging of Android APKs.
          • Feature Overview
          • Step 1: Preprocess the Android APK Parent Package
          • Step 2: Write the Channel Information into the APK Package with EdgeOne Edge Functions
      • Canary Release and Region-specific Execution
      • Adaptive Image Format Conversion via Edge Functions
      • Two Ways to Implement CDN Origin-pull Via Edge Function: Fetch and Passthrough
  • KV Storage
    • Overview
    • Operation Guide
  • Edge reasoning
    • Edge Inference Overview
    • Quick Guide

Cookies

Cookies provides a set of cookie operation APIs.
Note:
A collection of Cookie objects is managed by the Cookies object using name + domain + path as the unique key.

Constructor

new Cookies(cookieStr?: string, isSetCookie?: boolean): Cookies;

Parameters

Parameter Name
Type
Required
Description
cookieStr
string
No
Cookie string or Set-Cookie string.
isSetCookie
boolean
No
Whether the cookieStr parameter is a Set-Cookie string. Defaults to false.

Methods

get

cookies.get(name?: string): null | Cookie | Array<Cookie>;
Get the Cookie object with the specified name. If multiple name matches exist, an array of Cookie objects is returned.

Parameters

Parameter Name
Type
Required
Description
name
string
No
Cookie name. Values:
Default name
Indicates obtaining all Cookie objects.
Specified name
Indicates obtaining the Cookie object with the specified name. If multiple matches exist, a Cookie array is returned.
The properties of the Cookie object are as follows. For details, see MDN official documentation Set-Cookie.
Property Name
Type
Read-Only
Description
name
string
Yes
Cookie name.
value
string
Yes
Cookie value.
domain
string
Yes
Domain for the Cookie.
path
string
Yes
Path for the Cookie.
expires
string
Yes
Maximum validity period of the Cookie. The value must comply with the HTTP Date header standard.
max_age
string
Yes
The Cookie expires after max_age seconds. The unit is seconds (s).
samesite
string
Yes
Controls protection against Cookie cross-site request forgery (CSRF) attacks.
httponly
boolean
Yes
Prohibits JavaScript from accessing the Cookie. The Cookie can only be carried in HTTP requests.
secure
boolean
Yes
The Cookie can only be carried over HTTPS.

set

cookies.set(name: string, value: string, options?: Cookie): boolean;
Adds a cookie by overwriting any existing one. Returns true if the cookie is added successfully, or false if the addition fails because the number of cookies exceeds the limit. For details, see cookies size limit.
Attention
Add a Cookie by overwriting any existing one, using name + domain + path as the unique key.

Parameters

Parameter Name
Type
Required
Description
name
string
Yes
Cookie name.
value
string
Yes
Cookie value.
options
No
Cookie attribute configuration item.

append

cookies.append(name: string, value: string, options?: Cookie): boolean;
Appends a Cookie for scenarios where the same name has multiple values. Returns true if the cookie is added successfully, or false if the addition fails because the value is duplicated or the number of cookies exceeds the limit. For details, see cookies size limit.
Attention
Append a Cookie, using name + domain + path as the unique key.

Parameters

Parameter Name
Type
Required
Description
name
string
Yes
Cookie name.
value
string
Yes
Cookie value.
options
No
Cookie attribute configuration item.

remove

cookies.remove(name: string, options?: Cookie): boolean;
Delete the Cookie.
Attention
Delete the Cookie, using name + domain + path as the unique key.

Parameters

Parameter Name
Type
Required
Description
name
string
Yes
Cookie name.
options
No
Cookie attribute configuration item, where the domain and path attributes support * to match all.

Limits

Automatic Escaping of Special Characters

Characters in the name value, including " ( ) , / : ; < = > ? @ [ ] \ { }, 0x00 to 0x1F, and 0x7F to 0xFF, are automatically escaped.
Characters in the value, including , ; " \, 0x00 to 0x1F, and 0x7F to 0xFF, are automatically escaped.

Cookie Size Limit

The size of the name attribute of a Cookie does not exceed 64B.
The total size of the Cookie attributes value, domain, path, expires, max_age, samesite does not exceed 1KB.
The total length of all fields in escaped cookies does not exceed 4KB.
The total number of Cookie objects contained in cookies does not exceed 64.

Sample Code

function handleEvent(event) {
const request = event.request;

// Parse the Cookie request header (invalid fragments are automatically ignored)
const cookies = new Cookies(request.headers.get('Cookie') || '');

// Read the login state marker cookie
// get may return null / a single Cookie / an array of Cookies (duplicates with the same name)
const loginState = cookies.get('login_state');
const loggedIn = loginState !== null &&
!Array.isArray(loginState) &&
loginState.value === '1';

if (!loggedIn) {
// Not logged in: redirect to the login page with the return URL
const backUrl = encodeURIComponent(request.url);
return event.respondWith(Response.redirect(`https://www.example.com/login?back_url=${backUrl}`, 302));
}

// Logged in: allow origin-pull
return;
}

References