Quick overview
Installation
The Edge Runtime is available as Node.js package. You can install it with your favorite package manager:
npm install edge-runtime
Usage
Once it's installed, you can evaluate any script into the runtime context:
import { EdgeRuntime } from 'edge-runtime'
const runtime = new EdgeRuntime()
const result = await runtime.evaluate("fetch('https://example.vercel.sh')")
console.log(result)
The runtime provides you with ready to use Web APIs that can be extended if needed:
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)
You can load some initial code, for example, to be ready for receiving fetch events:
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())
and expose it locally to be used via HTTP:
import { EdgeRuntime, runServer } from 'edge-runtime'
import { onExit } from 'signal-exit'
import fetch from 'node-fetch'
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())
After that, you will be ready to hit your local server from your terminal:
curl http://[::]:3000?url=https://example.vercel.sh