How can I make my library compatible with the Vercel Edge Functions runtime?

Learn how to make your library or SDK compatible with Vercel Edge Functions and Vercel Edge Middleware.
Last updated on September 24, 2024
FrameworksFunctions

This guide will help make your npm package or SDK compatible with the Edge Runtime, a lightweight subset of Node.js. By becoming compatible with the Edge Runtime, you can use Vercel Edge Functions and Vercel Edge Middleware.

This guide will cover the supported and unsupported APIs and library recommendations.

Benefits of adopting the Edge Runtime for your library include:

  • Built on Web standard APIs and compatible with many Node.js APIs
  • Interoperability with every runtime environment, including the client, server, and edge

The Edge Runtime provides a subset of Web APIs such as fetch, Request, and Response. This lightweight API layer is built to be performant and execute code with minimal latency.

For a complete list of supported APIs, please refer to the Edge Runtime documentation.

The Edge Runtime has some restrictions:

  • Some Node.js APIs other than the ones listed in the documentation are not supported. For example, you can't read or write to the filesystem.
  • node_modules can be used, as long as they implement ES Modules and do not use native Node.js APIs.
  • Calling require directly is not allowed. Use import instead.

The following JavaScript language features are disabled, and will not work:

  • eval
  • new Function(evalString)
  • WebAssembly.compile
  • WebAssembly.instantiate

To ensure compatibility with the Edge Runtime, consider using the following alternatives to libraries or APIs that aren't compatible:

  • For data fetching, prefer using the Web fetch API instead of axios or cross-fetch.
  • For authentication, prefer using node-jose.
  • For ID generation, prefer using nanoid.

The following AI providers SDKs are compatible with the Edge Runtime:

You can check if your function is running on the Edge Runtime by checking the global globalThis.EdgeRuntime property. This can be helpful if you need to validate that your function is running on the Edge Runtime in tests or if you need to use a different API depending on the runtime.

if (typeof EdgeRuntime !== 'string') {
// Dead-code elimination is enabled for the code inside this block
}
Determine if you are using the Edge Runtime.

By following this guide and adapting your library or SDK to be compatible with the Edge Runtime, you can take advantage of the performance benefits and features of Vercel Edge Functions and Vercel Edge Middleware.

Couldn't find the guide you need?