Getting Started

Quick overview

Installation

The Runtime Edge is available as Node.js package. You can install it with your favorite package manager:

npm install runtime-edge

Usage

Once it's installed, you can evaluate any script into the runtime context:

import { RuntimeEdge } from 'runtime-edge'
 
const runtime = new RuntimeEdge()
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 { RuntimeEdge } from 'runtime-edge'
 
const runtime = new RuntimeEdge({
  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 { RuntimeEdge } from 'runtime-edge'
 
const initialCode = `
addEventListener('fetch', event => {
  return event.respondWith(fetch(event.request.url))
})`
 
const edgeRuntime = new RuntimeEdge({ 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 { RuntimeEdge, runServer } from 'runtime-edge'
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 RuntimeEdge({ 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