Standalone scripts
Standalone functions in bunny.net Edge Scripts allow you to run custom scripts as close as possible to bunny.net's CDN network. These functions act as substitutes for an origin server, enabling you to handle HTTP requests directly at the edge. You can think of them as infinitely scalable Node.js scripts that run on bunny.net's global infrastructure.
By using standalone functions, you can serve dynamic content, implement custom logic, and manipulate requests and responses directly at the edge. This approach eliminates the need for an origin server in many scenarios, allowing you to build powerful, low-latency applications.
The serve
function provided by the bunny.net Edge Script SDK allows you to define a handler for incoming HTTP requests. This handler can process requests and return responses directly, without passing them to an origin server.
Example script
Let's look at an example script that demonstrates how to use a standalone function to implement A/B testing based on a custom header:
import * as BunnySDK from "https://esm.sh/@bunny.net/[email protected]";
BunnySDK.net.http.serve(
async (req) => {
console.log(`[INFO]: ${req.method} - ${req.url}`);
let origin = "bunny.net";
let newOrigin = "dash.bunny.net/auth/register";
// Retrieve scenario header value
let scenario = req.headers.get("X-AB");
// We properly remap the port & the protocol as we could be in a local case
// where the port is 8080 for instance
let url = new URL(req.url);
url.port = "443";
url.protocol = "https";
if (scenario === "new") {
url.host = newOrigin;
} else {
url.host = origin;
}
return fetch(url);
},
);
You can run this example locally using Deno deno run -A script.ts.
:
# Case A
curl http://127.0.0.1:8080/ --header 'X-AB: new'
# Case B
curl http://127.0.0.1:8080/
Serve function
The serve
function starts an HTTP server that listens for incoming requests and handles them using the provided handler function. If you do not specify a listener, a default one is assigned, which is especially useful when running the script within bunny.net's network.
If you do not provide a listener, the server will randomly assign one when running locally. When running within bunny.net's network, the listener is automatically assigned, even if you specify one.
Signature:
declare const serve: (handler: (request: Request) => Response |
Promise<Response>): ServerHandler
declare const serve: (listener: { port: number; hostname: string }, handler: (request: Request) => Response |
Promise<Response>): ServerHandler
Updated about 1 month ago