### Install Edge Runtime Node.js Package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/getting-started.mdx Install the Edge Runtime package using npm. ```sh npm install edge-runtime ``` -------------------------------- ### Test Local Edge Server with Curl Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/getting-started.mdx Example curl command to interact with the locally running Edge Runtime server, passing a URL parameter. ```sh curl http://[::]:3000?url=https://example.vercel.sh ``` -------------------------------- ### Handle Fetch Events with Initial Code in Edge Runtime Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/getting-started.mdx Illustrates how to load initial code into Edge Runtime to set up an event listener for fetch events and dispatch a fetch request. ```js import { EdgeRuntime } from 'edge-runtime' const initialCode = ` addEventListener('fetch', event => { return event.respondWith(fetch(event.request.url)) })` const edgeRuntime = new EdgeRuntime({ initialCode }) const response = await edgeRuntime.dispatchFetch('https://example.vercel.sh') // If your code logic performs asynchronous tasks, you should await them. // https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil await response.waitUntil() console.log(await response.text()) ``` -------------------------------- ### Expose Edge Runtime Locally via HTTP Server Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/getting-started.mdx Demonstrates how to run an Edge Runtime instance as a local HTTP server, handling fetch events and gracefully shutting down on exit. ```js import { EdgeRuntime, runServer } from 'edge-runtime' import { onExit } from 'signal-exit' const initialCode = ` addEventListener('fetch', event => { const { searchParams } = new URL(event.request.url) const url = searchParams.get('url') return event.respondWith(fetch(url)) })` const edgeRuntime = new EdgeRuntime({ initialCode }) const server = await runServer({ runtime: edgeRuntime, port: 3000 }) console.log(`> Edge server running at ${server.url}`) onExit(() => server.close()) ``` -------------------------------- ### Evaluate Script in Edge Runtime Context Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/getting-started.mdx Demonstrates how to initialize EdgeRuntime and evaluate a script that performs a fetch request. ```js import { EdgeRuntime } from 'edge-runtime' const runtime = new EdgeRuntime() const result = await runtime.evaluate("fetch('https://example.vercel.sh')") console.log(result) ``` -------------------------------- ### Extend Web APIs in Edge Runtime Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/getting-started.mdx Shows how to extend the default Web APIs provided by Edge Runtime, specifically modifying the fetch behavior to prepend 'https://' to URLs. ```js import { EdgeRuntime } from 'edge-runtime' const runtime = new EdgeRuntime({ extend: (context) => { const rawFetch = context.fetch.bind(context.fetch) context.fetch = async (input: RequestInfo | URL, init?: RequestInit) => rawFetch( typeof input === 'string' && !input.startsWith('https://') ? `https://${input}` : String(input), init ) return context } }) const result = await runtime.evaluate("fetch('example.com')") console.log(result) ``` -------------------------------- ### Install @edge-runtime/ponyfill Package Source: https://github.com/vercel/edge-runtime/blob/main/packages/ponyfill/README.md Instructions for installing the @edge-runtime/ponyfill package using npm, yarn, or pnpm. ```sh npm install @edge-runtime/ponyfill --save ``` ```sh yarn add @edge-runtime/ponyfill --dev ``` ```sh pnpm install @edge-runtime/ponyfill --save ``` -------------------------------- ### Install @edge-runtime/vm package Source: https://github.com/vercel/edge-runtime/blob/main/packages/vm/README.md This snippet provides commands to install the `@edge-runtime/vm` package using various JavaScript package managers. The package offers low-level bindings for creating Web Standard contexts. ```sh npm install @edge-runtime/vm --save ``` ```sh yarn add @edge-runtime/vm --dev ``` ```sh pnpm install @edge-runtime/vm --save ``` -------------------------------- ### Install @edge-runtime/format package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/format.mdx Instructions to install the @edge-runtime/format package using npm. ```Shell npm install @edge-runtime/format ``` -------------------------------- ### Install @edge-runtime/vm package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/vm.mdx Instructions to install the @edge-runtime/vm package using npm. ```sh npm install @edge-runtime/vm ``` -------------------------------- ### Start Edge Runtime interactive REPL session Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/cli.mdx Starts an interactive read-eval-print loop (REPL) session with the Edge Runtime, allowing users to execute commands directly and explore APIs. ```bash edge-runtime --repl ``` -------------------------------- ### EdgeVM extend option example Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/vm.mdx Example demonstrating how to use the 'extend' option to add a 'process.env' object to the VM context. ```js const vm = new EdgeVM({ extend: (context) => Object.assign(context, { process: { env: { NODE_ENV: 'development' } }, }), }) ``` -------------------------------- ### Install Edge Runtime CLI globally Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/cli.mdx Installs the Edge Runtime command-line interface globally on your system using npm, allowing it to be run from any terminal. ```sh npm -g install edge-runtime ``` -------------------------------- ### Install @edge-runtime/node-utils Package Source: https://github.com/vercel/edge-runtime/blob/main/packages/node-utils/README.md Instructions for installing the @edge-runtime/node-utils package using various Node.js package managers. This package provides helpers for running edge-compliant code in Node.js. ```sh npm install @edge-runtime/node-utils --save ``` ```sh yarn add @edge-runtime/node-utils --dev ``` ```sh pnpm install @edge-runtime/node-utils --save ``` -------------------------------- ### Run local HTTP server with Edge Runtime CLI Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/cli.mdx Starts a local HTTP server using the Edge Runtime, serving a specified JavaScript file (e.g., examples/fetch.js) as the application entry point. ```bash edge-runtime --listen examples/fetch.js ``` -------------------------------- ### Install @edge-runtime/jest-environment Source: https://github.com/vercel/edge-runtime/blob/main/packages/jest-environment/README.md Instructions for installing the @edge-runtime/jest-environment package, which provides a Jest integration for running assertions in an Edge Runtime context. Different package managers (npm, yarn, pnpm) are supported. ```sh npm install @edge-runtime/jest-environment --save ``` ```sh yarn add @edge-runtime/jest-environment --dev ``` ```sh pnpm install @edge-runtime/jest-environment --save ``` -------------------------------- ### Install Edge Runtime Ponyfill Package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/ponyfill.mdx Instructions to install the @edge-runtime/ponyfill package using npm. This package includes built-in TypeScript support. ```sh npm install @edge-runtime/ponyfill ``` -------------------------------- ### Install @edge-runtime/primitives Package Source: https://github.com/vercel/edge-runtime/blob/main/packages/primitives/README.md Commands to install the `@edge-runtime/primitives` package using different Node.js package managers (npm, yarn, pnpm). This package provides essential primitives for building Vercel Edge Runtime applications. ```sh npm install @edge-runtime/primitives --save ``` ```sh yarn add @edge-runtime/primitives --dev ``` ```sh pnpm install @edge-runtime/primitives --save ``` -------------------------------- ### runServer Function API Reference Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/runtime.mdx This section documents the `runServer` function, which sets up and starts an HTTP server from an Edge Runtime instance. It explains the `port` option for server binding and outlines methods like `url` for access, `waitUntil` for effect completion, and `close` for server shutdown. ```APIDOC runServer([options]): Creates an HTTP handler based on the given options and then immediately runs a server on the provided port. options: Any option provided will be passed against .createHandler, plus: port?: number The port to start the server. If none is provided it will use a random available port. methods: url: string The server URLs. waitUntil: () => Promise Waits for all current effects returning their result. close: () => Promise Waits for all the current effects and closes the server. If you call .close, it will implicitly call .waitUntil. ``` -------------------------------- ### Install edge-runtime package Source: https://github.com/vercel/edge-runtime/blob/main/packages/runtime/README.md Instructions to install the edge-runtime package using different Node.js package managers. The package enables running Edge Functions from the CLI or as a Node.js module. ```sh npm install edge-runtime --save ``` ```sh yarn add edge-runtime --dev ``` ```sh pnpm install edge-runtime --save ``` -------------------------------- ### Install @edge-runtime/jest-expect package Source: https://github.com/vercel/edge-runtime/blob/main/packages/jest-expect/README.md Instructions for installing the @edge-runtime/jest-expect package using npm, yarn, or pnpm. This package provides custom Jest matchers for Request/Response instances, useful for testing Edge Runtime applications. ```sh npm install @edge-runtime/jest-expect --save ``` ```sh yarn add @edge-runtime/jest-expect --dev ``` ```sh pnpm install @edge-runtime/jest-expect --save ``` -------------------------------- ### Install Edge Runtime Jest Expect Package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-expect.mdx Installs the @edge-runtime/jest-expect package using npm, providing Jest matchers for HTTP testing. ```sh npm install @edge-runtime/jest-expect ``` -------------------------------- ### Install @edge-runtime/format package Source: https://github.com/vercel/edge-runtime/blob/main/packages/format/README.md Instructions for installing the `@edge-runtime/format` package using various Node.js package managers like npm, yarn, and pnpm. This package provides a `util.inspect` implementation for serializing values. ```Shell npm install @edge-runtime/format --save ``` ```Shell yarn add @edge-runtime/format --dev ``` ```Shell pnpm install @edge-runtime/format --save ``` -------------------------------- ### Handle Fetch Events with Edge Runtime Module Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/runtime.mdx This example demonstrates using `EdgeRuntime` as a module to intercept and respond to fetch events. It shows how to initialize the runtime with `initialCode`, dispatch a fetch request, and properly await asynchronous operations using `waitUntil`. ```js import { EdgeRuntime } from 'edge-runtime' const initialCode = ` addEventListener('fetch', event => { const { searchParams } = new URL(event.request.url) const url = searchParams.get('url') return event.respondWith(fetch(url)) })` const runtime = new EdgeRuntime({ initialCode }) const response = await runtime.dispatchFetch( 'http://vercel.com?url=https://example.vercel.sh', ) // If your code logic performs asynchronous tasks, you should await them. // https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil await response.waitUntil() // `response` is Web standard, you can use any of it's methods console.log(response.status) ``` -------------------------------- ### Install @edge-runtime/node-utils Package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx This command installs the @edge-runtime/node-utils package using npm, providing utilities for running web-compliant code in Node.js. It includes built-in TypeScript support. ```sh npm install @edge-runtime/node-utils ``` -------------------------------- ### Install Edge Runtime Cookies Package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/cookies.mdx Installs the @edge-runtime/cookies package using npm or yarn, providing necessary dependencies for cookie management in Edge environments. ```sh npm install @edge-runtime/cookies ``` -------------------------------- ### Install Edge Runtime Package with npm Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/runtime.mdx This snippet provides the command to install the `edge-runtime` package using npm. The package comes with built-in TypeScript support, simplifying development. ```sh npm install edge-runtime ``` -------------------------------- ### Install Edge Runtime Jest Environment Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-environment.mdx Provides instructions for installing the @edge-runtime/jest-environment package using npm, enabling Jest tests to run against the Edge Runtime environment. ```sh npm install @edge-runtime/jest-environment ``` -------------------------------- ### Install Edge Runtime Primitives with npm Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/primitives.mdx Installs the @edge-runtime/primitives package using npm, saving it as a dependency in the project. This package includes built-in TypeScript support. ```sh npm install @edge-runtime/primitives --save ``` -------------------------------- ### Install Edge Runtime Types Package Source: https://github.com/vercel/edge-runtime/blob/main/packages/types/README.md Instructions for installing the `@edge-runtime/types` package using various Node.js package managers like npm, yarn, and pnpm. This package provides global TypeScript types for the Edge Runtime. ```sh npm install @edge-runtime/types --save ``` ```sh yarn add @edge-runtime/types --dev ``` ```sh pnpm install @edge-runtime/types --save ``` -------------------------------- ### Install Edge Runtime User Agent Package Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/user-agent.mdx This command installs the @edge-runtime/user-agent package using npm, making it available for use in your project. It includes built-in TypeScript support. ```sh npm install @edge-runtime/user-agent ``` -------------------------------- ### Install Edge Runtime Types with npm Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/types.mdx This command installs the @edge-runtime/types package using npm. This package provides the necessary TypeScript global types for developing with Edge Runtime. ```sh npm install @edge-runtime/types ``` -------------------------------- ### Install and Precompile Edge Runtime in Next.js Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/upgrading-nextjs.mdx After updating the 'edge-runtime' and '@edge-runtime' versions in your 'package.json' files, use these commands to install the updated dependencies and then precompile the Next.js package. ```Shell pnpm install cd packages/next npm run ncc-compiled ``` -------------------------------- ### Install @edge-runtime/user-agent Package Source: https://github.com/vercel/edge-runtime/blob/main/packages/user-agent/README.md Instructions for installing the @edge-runtime/user-agent package using various Node.js package managers: npm, yarn, and pnpm. This utility provides user-agent parsing compatible with Edge Runtime environments. ```sh npm install @edge-runtime/user-agent --save ``` ```sh yarn add @edge-runtime/user-agent --dev ``` ```sh pnpm install @edge-runtime/user-agent --save ``` -------------------------------- ### Install @edge-runtime/cookies Package Source: https://github.com/vercel/edge-runtime/blob/main/packages/cookies/README.md Instructions for installing the @edge-runtime/cookies package using various Node.js package managers (npm, yarn, pnpm). This package provides cookie helper utilities compatible with Vercel's Edge Runtime. ```sh npm install @edge-runtime/cookies --save ``` ```sh yarn add @edge-runtime/cookies --dev ``` ```sh pnpm install @edge-runtime/cookies --save ``` -------------------------------- ### Example Jest Test Passing in Node.js Environment Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-environment.mdx Demonstrates a Jest test that successfully executes in a standard Node.js environment, showcasing basic JavaScript evaluation using `eval`. ```js // jest --env node // ✅ Pass it('should return the correct value', () => { let val = eval('2 + 2') expect(val).toBe(4) }) ``` -------------------------------- ### Extend EdgeVM context to modify fetch behavior Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/vm.mdx Shows how to extend the EdgeVM context to modify the default fetch behavior, specifically to prepend 'https://' to URLs that don't start with it. ```js const edgeVM = new EdgeVM({ extend: (context) => { const rawFetch = context.fetch.bind(context.fetch) context.fetch = async (input: RequestInfo | URL, init?: RequestInit) => rawFetch( typeof input === 'string' && !input.startsWith('https://') ? `https://${input}` : String(input), init ) return context }, }) const { url, status } = await edgeVM.evaluate("fetch('edge-ping.vercel.app')") console.log(`ping to ${url} returned ${status}`) ``` -------------------------------- ### Transform Web Request Handler to Node.js Handler Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx This TypeScript example demonstrates how to use `buildToNodeHandler` to convert a web-compliant request handler (using Request and Response) into a Node.js compatible handler. It sets up an HTTP server, transforms the handler, and processes a POST request. ```ts import { once } = from 'node:events' import { createServer } from 'node:http' import { buildToNodeHandler } from '@edge-runtime/node-utils' // 1. builds a transformer, using Node.js@18 globals, and a base url for URL constructor. const transformToNode = buildToNodeHandler(global, { defaultOrigin: 'http://example.com', }) const server = await createServer( // 2. takes an web compliant request handler, that uses Web globals like Request and Response, // and turn it into a Node.js compliant request handler. transformToNode(async (req: Request) => new Response(req.body)) ) // 3. start the node.js server server.listen() await once(server, 'listening') // 4. invoke the request handler const response = await fetch( `http://localhost:${(server.address() as AddressInfo).port}`, { method: 'POST', body: 'hello world' } ) console.log(await response.text()) // is 'hello world' await server.close() ``` -------------------------------- ### Parse User Agent Directly from Request Object in Edge Runtime Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/user-agent.mdx This example shows an alternative way to parse user agent information by directly passing the Request instance to the userAgent method. It simplifies the process and returns the same detailed user agent object. ```ts import { userAgent } from '@edge-runtime/user-agent' export default (request: Request) => { return Response.json(userAgent(request)) // => { // browser: { // major: '83', // name: 'Chrome', // version: '83.0.4103.116', // }, // cpu: { architecture: 'amd64' }, // engine: { // name: 'Blink', // version: '83.0.4103.116', // }, // isBot: false, // os: { // name: 'Windows', // version: '10', // }, // ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)…' // } } ``` -------------------------------- ### Parse User Agent String from Request Headers in Edge Runtime Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/user-agent.mdx This example demonstrates how to use the userAgentFromString method to parse a user agent string obtained from a Request object's headers. It returns a structured object containing browser, CPU, engine, and OS details. ```js import { userAgentFromString } from '@edge-runtime/user-agent' export default (request: Request) => { const userAgent = request.headers.get('user-agent') userAgentFromString(userAgent) return Response.json(userAgent(request)) // => { // browser: { // major: '83', // name: 'Chrome', // version: '83.0.4103.116', // }, // cpu: { architecture: 'amd64' }, // engine: { // name: 'Blink', // version: '83.0.4103.116', // }, // isBot: false, // os: { // name: 'Windows', // version: '10', // }, // ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)…' // } } ``` -------------------------------- ### Example Jest Test Failing in Edge Runtime Environment Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-environment.mdx Illustrates a Jest test that fails when run with the @edge-runtime/jest-environment due to the Edge Runtime's security policy, which disallows code generation from strings (e.g., via `eval`), resulting in an `EvalError`. ```js // jest --env @edge-runtime/jest-environment // ❌ Fail // Error name: "EvalError" // Error message: "Code generation from strings disallowed for this context" it('should return the correct value', () => { let val = eval('2 + 2') expect(val).toBe(4) }) ``` -------------------------------- ### EdgeRuntime Class Constructor API Reference Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/runtime.mdx This API documentation details the `EdgeRuntime` class constructor, including its `options` parameter. It specifies that `initialCode` can be provided for VM evaluation and notes that the class inherits methods from `@edge-runtime/vm`, adding `VercelRuntime` for version retrieval. ```APIDOC EdgeRuntime([options]): Creates a new Edge Runtime instance. options: Any option provided will be passed against @edge-runtime/vm. initialCode?: string Some initial code to be evaluated as the VM for the runtime is created. methods: Inherits from @edge-runtime/vm, plus: VercelRuntime: string Returns the runtime version. ``` -------------------------------- ### Configure Next.js App with Nextra Theme and Layout Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/_app.mdx This snippet sets up the main `_app.js` (or equivalent) file for a Next.js application, integrating global CSS styles and the `nextra-theme-docs`. It also implements a flexible layout system by checking for a `getLayout` function on the page component, allowing individual pages to define their own layout wrappers. ```javascript import '../styles.css' import 'nextra-theme-docs/style.css' export default function Nextra({ Component, pageProps }) { const getLayout = Component.getLayout || ((page) => page) return getLayout( <> , ) } ``` -------------------------------- ### EdgeVM constructor options API Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/vm.mdx Documentation for the EdgeVM constructor and its available options, including codeGeneration, extend, and requireCache. ```APIDOC new EdgeVM([options]) options: codeGeneration?: object Description: Provides code generation options to vm.createContext#options. Default: { strings: false, wasm: true } extend?: (context: VMContext) => ExtendedDictionary Description: Allows to extend the VMContext. Note: Must return a contextified object so ideally it should return the same reference it receives. requireCache?: Map Description: Provides an initial map to the require cache, if none is given, it will be initialized to an empty map. ``` -------------------------------- ### EdgeVM instance methods API Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/vm.mdx Documentation for the methods available on an EdgeVM instance: evaluate, require, requireInContext, and requireInlineInContext. ```APIDOC methods: evaluate: (code: string): () => Promise Description: Allows you to run arbitrary code within the VM. require: (filepath: string) Description: Allows you to require a CommonJS module referenced in the provided file path within the VM context. It will return its exports. requireInContext: (filepath: string) Description: Same as require but it will copy each of the exports in the context of the VM. Exports can then be used inside of the VM with an evaluated script. requireInlineInContext: (code: string) Description: Same as requireInContext but allows you to pass the code instead of a reference to a file. Note: It will create a temporary file and then load it in the VM Context. ``` -------------------------------- ### Accessing Edge Runtime APIs via Ponyfill Package (Recommended) Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/ponyfill.mdx This snippet shows the recommended way to use Edge Runtime APIs by importing them from the @edge-runtime/ponyfill package. This ensures consistent behavior and availability of APIs across different environments, leveraging the ponyfill's capabilities. ```js import { crypto, TextEncoder } from '@edge-runtime/ponyfill' const data = new TextEncoder().encode('Hello, world') const digest = await crypto.subtle.digest('SHA-256', content) ``` -------------------------------- ### Import and Log Edge Runtime Primitives in JavaScript Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/primitives.mdx Demonstrates how to import the @edge-runtime/primitives package and log its contents to the console, showing the available Web Standard APIs like AbortController, Blob, and Crypto. ```js import primitives from '@edge-runtime/primitives' console.log(primitives) // { // AbortController: [Getter], // AbortSignal: [Getter], // Blob: [Getter], // console: [Getter], // Crypto: [Getter], // CryptoKey: [Getter], // SubtleCrypto: [Getter], // crypto: [Getter], // TextDecoder: [Getter], // TextDecoderStream: [Getter], // … // } ``` -------------------------------- ### Initialize formatter with createFormat Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/format.mdx Imports the `createFormat` method from `@edge-runtime/format` and initializes a formatter instance. ```JavaScript import { createFormat } from '@edge-runtime/format' const format = createFormat() ``` -------------------------------- ### Evaluate arbitrary code in EdgeVM Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/vm.mdx Demonstrates how to create an EdgeVM instance and evaluate a simple fetch call within the VM context, then log the result. ```js import { EdgeVM } from '@edge-runtime/vm' const edgeVM = new EdgeVM() const promise = edgeVM.evaluate("fetch('https://edge-ping.vercel.app')") const { url, status } = await promise console.log(`ping to ${url} returned ${status}`) ``` -------------------------------- ### Run Edge Runtime Instance as Local HTTP Server Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/runtime.mdx This snippet illustrates how to transform an `EdgeRuntime` instance into a local HTTP server using the `runServer` function. It logs the server's dynamically assigned URL, making it easy to access the runtime via HTTP. ```js import { runServer, EdgeRuntime } from 'edge-runtime' const runtime = new EdgeRuntime() const server = await runServer({ runtime }) console.log(`Listening at ${server.url}`) ``` -------------------------------- ### createFormat API Reference Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/format.mdx API documentation for the `createFormat` method, which returns a formatter, including its optional parameters. ```APIDOC createFormat([options]): Returns a formatter method. options: formatError?: (error: Error) => string Customizes how errors should be printed. Default: error.toString() customInspectSymbol?: symbol Sets the symbol to be used for printing custom behavior. Default: edge-runtime.inspect.custom ``` -------------------------------- ### API: buildToFetchEvent Function Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx This function builds a transformer to create a `FetchEvent` from a Web `Request`. The returned event is linked to the request and includes a mocked `waitUntil()` method that throws on access. It requires Web global constructors as dependencies. ```APIDOC buildToFetchEvent(dependencies: object): toFetchEvent(request: Request): FetchEvent ``` -------------------------------- ### Use string substitutions (printf style) Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/format.mdx Illustrates the use of printf-style string substitutions (e.g., `%i` for integer) within the formatter. ```JavaScript format('The PI number is %i', Math.PI, '(rounded)') // => 'The PI number is 3 (rounded)' ``` -------------------------------- ### createHandler Function API Reference Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/runtime.mdx This documentation describes the `createHandler` function, responsible for generating a Node.js HTTP handler. It highlights the mandatory `runtime` instance and the optional `logger` parameter, which can be used for custom logging based on the `Logger` interface. ```APIDOC createHandler([options]): Creates a Node.js HTTP handler. options: runtime: EdgeRuntime The Edge Runtime instance to be used that should be previously declared. logger?: Logger The logger to be used. If none is provided there will be no logs. ``` -------------------------------- ### API: buildToRequest Function Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx This function builds a transformer to convert a Node.js `IncomingMessage` into a Web `Request` object. It requires Web global constructors as dependencies and options to handle the incoming URL. ```APIDOC buildToRequest(dependencies: object, options: object): toRequest(request: IncomingMessage, options: object): Request ``` -------------------------------- ### API: buildToHeaders Function Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx This function builds a transformer to convert Node.js `IncomingHttpHeaders` into Web `Request.headers`. It requires Web global constructors as dependencies. ```APIDOC buildToHeaders(dependencies: object): toHeaders(nodeHeaders: IncomingHttpHeaders): Headers ``` -------------------------------- ### Edge Runtime Web Standards APIs Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx Lists general web standards APIs implemented in the Edge Runtime, such as `AbortController`, `DOMException`, and `URLPattern`. These APIs provide fundamental functionalities for controlling operations, handling errors, and parsing URLs. ```APIDOC AbortController AbortSignal DOMException structuredClone URLPattern ``` -------------------------------- ### Format multiple objects Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/format.mdx Shows how the formatter can handle multiple arguments, concatenating their string representations. ```JavaScript format('The PI number is', Math.PI, '(more or less)') // => 'The PI number is 3.141592653589793 (more or less)' ``` -------------------------------- ### Evaluate inline script with Edge Runtime CLI Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/cli.mdx Executes a given JavaScript script directly from the command line using the Edge Runtime's --eval option, useful for quick evaluations and testing. ```bash edge-runtime --eval "Object.getOwnPropertyNames(this)" ``` -------------------------------- ### ResponseCookies API Methods Reference Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/cookies.mdx Detailed documentation for the methods available on the ResponseCookies instance, used for managing cookies that will be sent back to the HTTP client. ```APIDOC get: description: Takes a cookie 'name' and returns an object with 'name' and 'value'. If not found, returns 'undefined'. If multiple match, returns the first. parameters: name: string (cookie name) returns: { name: string, value: string } | undefined getAll: description: Similar to 'get', but returns a list of all cookies with a matching 'name'. If 'name' is unspecified, it returns all available cookies. parameters: name: string (optional, cookie name) returns: Array<{ name: string, value: string }> set: description: Takes an object with properties of 'CookieListItem' as defined in the W3C CookieStore API spec. parameters: cookie: CookieListItem object returns: void delete: description: Takes either a cookie 'name' or a list of names and removes the matching cookies. Returns 'true' for deleted and 'false' for undeleted cookies. parameters: name: string | string[] (cookie name or list of names) returns: boolean ``` -------------------------------- ### Format a JavaScript object Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/format.mdx Demonstrates how to use the initialized formatter to convert a JavaScript object, including Symbol properties, into a string representation. ```JavaScript const obj = { [Symbol.for('foo')]: 'bar' } format(obj) // => '{ [Symbol(foo)]: 'bar' }' ``` -------------------------------- ### API: buildToNodeHandler Function Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx This function builds a transformer to convert a web-compliant request handler (Promise | Response | null | undefined) into a Node.js compliant request handler (Promise | void). It requires Web globals as dependencies and supports options like `defaultOrigin`. ```APIDOC buildToNodeHandler(dependencies: object, options: object): toNodeHandler(handler: WebHandler): NodeHandler WebHandler: (req: Request) => Promise | Response | null | undefined NodeHandler: (req: IncomingMessage, res: ServerResponse) => Promise | void Limitations: `waitUntil` is not implemented yet. dependencies: object Description: List of Web globals used by the transformer function. Properties: - Request: (https://developer.mozilla.org/en-US/docs/Web/API/Request) - Headers: (https://developer.mozilla.org/en-US/docs/Web/API/Headers) - ReadableStream: (https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) - Uint8Array: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) - FetchEvent: (https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent) Usage Examples: // With global scope (Node.js 18+): import { buildToNodeHandler } from '@edge-runtime/node-utils' buildToNodeHandler(globals, { /* ... options */ }) // With @edge-runtime/primitives: import { buildToNodeHandler } from '@edge-runtime/node-utils' import * as primitives from '@edge-runtime/primitives' buildToNodeHandler(primitives, { /* ... options */ }) options: object Description: Options used to build the transformer function. Properties: defaultOrigin: string Description: The default origin used when the incoming host header is not provided, for constructing Request.url. ``` -------------------------------- ### Edge Runtime Web Stream APIs Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx Provides a list of Web Stream APIs supported by the Edge Runtime for handling streaming data, including readable, writable, and transform streams. These APIs are crucial for processing large datasets efficiently and incrementally. ```APIDOC ReadableStream ReadableStreamBYOBReader ReadableStreamDefaultReader TransformStream WritableStream WritableStreamDefaultWriter ``` -------------------------------- ### Supported V8 Primitives and Web APIs in Vercel Edge Runtime Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx This section details the JavaScript global objects, typed arrays, error constructors, and Web API functions that are natively supported and accessible within the Vercel Edge Runtime. Developers can rely on these standard features for their serverless functions, ensuring consistent behavior with the V8 engine. ```APIDOC V8 Primitives and Web APIs: - Array - ArrayBuffer - Atomics - BigInt - BigInt64Array - BigUint64Array - Boolean - clearInterval - clearTimeout - console - DataView - Date - decodeURI - decodeURIComponent - encodeURI - encodeURIComponent - Error - EvalError - Float32Array - Float64Array - Function - Infinity - Int8Array - Int16Array - Int32Array - Intl - isFinite - isNaN - JSON - Map - Math - Number - Object - parseFloat - parseInt - Promise - Proxy - queueMicrotask - RangeError - ReferenceError - Reflect - RegExp - Set - setInterval - setTimeout - SharedArrayBuffer - String - Symbol ``` -------------------------------- ### API: toOutgoingHeaders Function Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx This function converts Web `Request.headers` into Node.js `ServerResponse` `OutgoingHttpHeaders`. It includes special handling for `set-cookie` headers, splitting multiple values when necessary. ```APIDOC toOutgoingHeaders(headers: Headers): OutgoingHttpHeaders ``` -------------------------------- ### Edge Runtime Network APIs Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx Lists network-related APIs available in the Edge Runtime, including those for data transfer, event handling, and HTTP requests/responses. These APIs enable applications to interact with network resources and handle asynchronous operations. ```APIDOC Blob Event EventTarget fetch FetchEvent File FormData Headers PromiseRejectionEvent Request Response WebSocket ``` -------------------------------- ### RequestCookies API Methods Reference Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/cookies.mdx Detailed documentation for the methods available on the RequestCookies instance, used for managing cookies within an incoming HTTP request. ```APIDOC get: description: Takes a cookie name and returns an object with 'name' and 'value'. If not found, returns 'undefined'. If multiple match, returns the first. Cookie configuration (Max-Age, Path) is not available. parameters: name: string (cookie name) returns: { name: string, value: string } | undefined getAll: description: Similar to 'get', but returns a list of all cookies with a matching 'name'. If 'name' is unspecified, returns all available cookies. parameters: name: string (optional, cookie name) returns: Array<{ name: string, value: string }> set: description: Takes an object with properties of 'CookieListItem' as defined in the W3C CookieStore API spec. parameters: cookie: CookieListItem object returns: void delete: description: Takes either a cookie 'name' or a list of names and removes the matching cookies. Returns 'true' for deleted and 'false' for undeleted cookies. parameters: name: string | string[] (cookie name or list of names) returns: boolean has: description: Takes a cookie 'name' and returns a 'boolean' indicating if the cookie exists ('true') or not ('false'). parameters: name: string (cookie name) returns: boolean clear: description: Takes no argument and effectively removes the 'Cookie' header from the request. parameters: none returns: void ``` -------------------------------- ### Configure Jest for Edge Runtime Matchers Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-expect.mdx Adds @edge-runtime/jest-expect to Jest's setupFilesAfterEnv configuration, ensuring the matchers are available in your test environment. ```js // See https://jestjs.io/docs/configuration#setupfilesafterenv-array setupFilesAfterEnv: ['@edge-runtime/jest-expect'], ``` -------------------------------- ### Accessing Edge Runtime APIs from Global Scope (Avoid) Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/ponyfill.mdx This snippet demonstrates how Edge Runtime APIs like TextEncoder and crypto.subtle might be accessed directly from the global scope. This approach is generally not recommended when using the ponyfill package for cross-environment compatibility. ```js const data = new TextEncoder().encode('Hello, world') const digest = await crypto.subtle.digest('SHA-256', content) ``` -------------------------------- ### Logger Interface TypeScript Definition Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/runtime.mdx This snippet provides the TypeScript definition for the `Logger` interface, used for structured logging within the `edge-runtime` package. It includes `LoggerOptions` for configuration and defines various logging methods such as `debug`, `error`, `info`, and `quotes`. ```ts interface LoggerOptions { color?: keyof Colors withHeader?: boolean withBreakline?: boolean } interface Logger { (message: string, opts?: LoggerOptions): void debug(message: string, opts?: LoggerOptions): void error(message: string, opts?: LoggerOptions): void info(message: string, opts?: LoggerOptions): void quotes(str: string): string } ``` -------------------------------- ### Edge Runtime Web Crypto APIs Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx Outlines Web Crypto APIs available in the Edge Runtime for cryptographic operations, including `crypto`, `CryptoKey`, and `SubtleCrypto`. These APIs enable secure operations like hashing, encryption, and digital signatures. ```APIDOC crypto CryptoKey SubtleCrypto ``` -------------------------------- ### Vercel Edge Runtime Unsupported APIs and Features Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx This section details the APIs and JavaScript language features that are not supported within the Vercel Edge Runtime. It highlights restrictions such as the absence of native Node.js APIs, the requirement for ES Modules in `node_modules`, and the disabling of `eval` and `new Function()` for security and performance reasons. ```APIDOC Unsupported APIs: - Native Node.js APIs: Not supported (e.g., filesystem access). - node_modules: Only supported if they implement ES Modules and do not use native Node.js APIs. - require: Direct calls to `require` are not allowed; use ES Modules instead. Disabled JavaScript Language Features: - eval: Evaluates JavaScript code represented as a string. - new Function(evalString): Creates a new function with the code provided as an argument. ``` -------------------------------- ### Customize object inspection with customInspectSymbol Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/format.mdx Demonstrates how to define a custom inspection behavior for an object using `Symbol.for('edge-runtime.inspect.custom')` to control its string representation. ```JavaScript const customInspectSymbol = Symbol.for('edge-runtime.inspect.custom') class Password { constructor(value) { Object.defineProperty(this, 'password', { value, enumerable: false, }) } toString() { return 'xxx' } [customInspectSymbol]() { return { password: `<${this.toString()}>`, } } } format(new Password('r0sebud')) // => { password: '' } ``` -------------------------------- ### Configure Edge Runtime TypeScript types in tsconfig.json Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/typescript-support.mdx To ensure Edge Runtime TypeScript types are loaded globally, add the '@edge-runtime/types' package to the 'types' array within the 'compilerOptions' section of your tsconfig.json file. This makes the types available throughout your project. ```json { "compilerOptions": { "types": ["@edge-runtime/types"] } } ``` -------------------------------- ### Edge Runtime Encoding APIs Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx Details APIs for encoding and decoding data, such as text and base64 conversions, within the Edge Runtime environment. These utilities are essential for handling various data formats and ensuring proper data transmission. ```APIDOC TextDecoder TextDecoderStream TextEncoder TextEncoderStream atob btoa ``` -------------------------------- ### Configure Edge Runtime Types in tsconfig.json Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/types.mdx This JSON snippet demonstrates how to include the @edge-runtime/types package in your tsconfig.json file. Adding it to the compilerOptions.types array ensures that the global types are automatically loaded and available across your TypeScript project. ```json { "compilerOptions": { "types": ["@edge-runtime/types"] } } ``` -------------------------------- ### Load Edge Runtime TypeScript types with triple-slash directive Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/typescript-support.mdx As an alternative to tsconfig.json, you can load Edge Runtime TypeScript types directly in a JavaScript or TypeScript file using a triple-slash reference directive. This explicitly declares a dependency on the types. ```js /// ``` -------------------------------- ### Access and Manipulate Response Cookies with ResponseCookies Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/cookies.mdx Demonstrates how to use the ResponseCookies constructor to set and delete cookies that will persist in the HTTP client. This involves manipulating a Headers object which is then passed to the Response. ```ts import { ResponseCookies } from '@edge-runtime/cookies' function handleRequest(req: Request) { const cookieKey = 'cookie-name' const headers = new Headers() const responseCookies = new ResponseCookies(headers) responseCookies.set('cookie-name', 'cookie-value', { maxAge: 1000 }) // make cookie persistent for 1000 seconds responseCookies.delete('old-cookie') return new Response(null, { headers, status: 200 }) } ``` -------------------------------- ### Build Transformer for Node.js Readable to Web ReadableStream Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx Builds a transformer function that converts a Node.js Readable stream (typically, an IncomingMessage's payload) into a Web ReadableStream. This enables Node.js stream data to be consumed by Web APIs and browser-compatible stream consumers. ```APIDOC buildToReadableStream(dependencies): toReadableStream(stream: Readable): ReadableStream dependencies: Dependencies required to build the transformer. stream: The Node.js Readable stream to convert (e.g., IncomingMessage's payload). ``` -------------------------------- ### Convert Web ReadableStream to Node.js Readable Stream Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/node-utils.mdx Converts a Web ReadableStream (typically, the Response.body) into a Node.js Readable stream. This utility is crucial for integrating Web API stream sources with Node.js stream processing logic. ```APIDOC toToReadable(webStream: ReadableStream, options: object): Readable webStream: The Web ReadableStream to convert (e.g., Response.body). options: An optional object for configuration. ``` -------------------------------- ### Check Vercel Edge Runtime Availability in TypeScript Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/features/available-apis.mdx This TypeScript snippet demonstrates how to check for the presence of the `EdgeRuntime` global property, which can be used to identify if the code is running within the Vercel Edge Runtime. Code inside the conditional block is subject to dead-code elimination if `EdgeRuntime` is not a string. ```TypeScript if (typeof EdgeRuntime !== 'string') { // dead-code elimination is enabled for the code inside this block } ``` -------------------------------- ### Access and Manipulate Request Cookies with RequestCookies Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/cookies.mdx Demonstrates how to use the RequestCookies constructor to access and manipulate incoming request cookies. Mutations are performed in place and update the 'Cookie' header in the provided Request object, though these changes are not readable by the client. ```ts import { RequestCookies } from '@edge-runtime/cookies' function handleRequest(req: Request) { const cookies = new RequestCookies(req.headers) cookies.get('cookie-name')?.value // undefined | string cookies.has('cookie-name') // boolean // do something... } ``` -------------------------------- ### Include TypeScript Types for Jest Matchers Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-expect.mdx Adds the TypeScript types for @edge-runtime/jest-expect to your tsconfig.json, providing type-checking for the Jest matchers. ```json // See https://www.typescriptlang.org/tsconfig#include "include": [ "node_modules/@edge-runtime/jest-expect" ] ``` -------------------------------- ### Reference Edge Runtime Types via Triple-Slash Directive Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/types.mdx This JavaScript/TypeScript comment, known as a triple-slash directive, explicitly references the @edge-runtime/types package. It's an alternative method to load the global types for Edge Runtime, typically used when you need to include types in a specific file rather than globally via tsconfig.json. ```js /// ``` -------------------------------- ### Test HTTP Status with .toHaveStatus Jest Matcher Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-expect.mdx Checks if an HTTP Response has a specific status code or message using the .toHaveStatus matcher. It supports both numeric codes and descriptive strings. ```js const response = new Response('OK') expect(response).toHaveStatus(200) expect(response).toHaveStatus('Successful') expect(response).not.toHaveStatus(201) ``` -------------------------------- ### Test Text Body with .toHaveTextBody Jest Matcher Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-expect.mdx Checks if an HTTP request or response body contains a specific text string using the .toHaveTextBody matcher. It's useful for verifying plain text content. ```js const request = new Request('http://example.com', { method: 'POST', body: 'Hello World' }) expect(request).toHaveTextBody('hello world') expect(request).not.toHaveTextBody('foo bar') ``` -------------------------------- ### Test JSON Body with .toHaveJSONBody Jest Matcher Source: https://github.com/vercel/edge-runtime/blob/main/docs/pages/packages/jest-expect.mdx Verifies if an HTTP request or response body is a specific JSON object using the .toHaveJSONBody matcher. It performs a deep comparison of the JSON content. ```js const response = Response.json({ hello: 'world' }) expect(response).toHaveJSONBody({ hello: 'world' }) expect(response).not.toHaveJSONBody({ foo: 'baz' }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.