Cloudflare Docs
Pages
Edit this page on GitHub
Set theme to dark (⇧+D)

Module support

Pages Functions provide support for several module types, much like Workers. This means that you can import and use external modules such as WebAssembly (Wasm), text and binary files inside your Functions code.

This guide will instruct you on how to use these different module types inside your Pages Functions.

​​ ECMAScript Modules

ECMAScript modules (or in short ES Modules) is the official, standardized module system for JavaScript. It is the recommended mechanism for writing modular and reusable JavaScript code.

ES Modules are defined by the use of import and export statements. Below is an example of a script written in ES Modules format, and a Pages Function that imports that module:

src/greeting.ts
export function greeting(name: string): string {
return `Hello ${name}!`;
}
functions/hello.ts
import { greeting } from "../src/greeting.ts";
export async function onRequest(context) {
return new Response(`${greeting("Pages Functions")}`);
}

​​ WebAssembly Modules

WebAssembly (abbreviated Wasm) allows you to compile languages like Rust, Go, or C to a binary format that can run in a wide variety of environments, including web browsers, Cloudflare Workers, Cloudflare Pages Functions, and other WebAssembly runtimes.

The distributable, loadable, and executable unit of code in WebAssembly is called a module.

Below is a basic example of how you can import Wasm Modules inside your Pages Functions code:

functions/meaning-of-life.ts
import addModule from "add.wasm";
export async function onRequest() {
const addInstance = await WebAssembly.instantiate(addModule);
return new Response(
`The meaning of life is ${addInstance.exports.add(20, 1)}`
);
}

​​ Text Modules

Text Modules are a non-standardized means of importing resources such as HTML files as a String.

To import the below HTML file into your Pages Functions code:

index.html
<!DOCTYPE html>
<html>
<body>
<h1>Hello Pages Functions!</h1>
</body>
</html>

Use the following script:

functions/hey.ts
import html from "../index.html";
export async function onRequest() {
return new Response(
html,
{
headers: { "Content-Type": "text/html" }
}
);
}

​​ Binary Modules

Binary Modules are a non-standardized way of importing binary data such as images as an ArrayBuffer.

Below is a basic example of how you can import the data from a binary file inside your Pages Functions code:

functions/data.ts
import data from "../my-data.bin";
export async function onRequest() {
return new Response(
data,
{
headers: { "Content-Type": "application/octet-stream" }
}
);
}