Edge Runtime

We recommend migrating from edge to Node.js for improved performance and reliability. Both runtimes run on Fluid compute with Active CPU pricing.

To convert your Vercel Function to use the Edge runtime, add the following code to your function:

app/api/my-function/route.ts
export const runtime = 'edge'; // 'nodejs' is the default
 
export function GET(request: Request) {
  return new Response(`I am an Vercel Function!`, {
    status: 200,
  });
}

If you're not using a framework, you must either add "type": "module" to your package.json or change your JavaScript Functions' file extensions from .js to .mjs

By default Edge Functions execute in the region closest to the incoming request. You can set one or more preferred regions using the route segment config preferredRegion or specify a regions key within a config object to set one or more regions for you functions to execute in

If your function depends on a data source, you may want it to be close to that source for fast responses.

To configure which region (or multiple regions) you want your function to execute in, pass the ID of your preferred region(s) in the following way:

The preferredRegion option can be used to specify a single region using a string value, or multiple regions using a string array. See the Next.js documentation for more information.

app/api/regional-example/route.ts
export const runtime = 'edge'; // 'nodejs' is the default
// execute this function on iad1 or hnd1, based on the connecting client location
export const preferredRegion = ['iad1', 'hnd1'];
export const dynamic = 'force-dynamic'; // no caching
 
export function GET(request: Request) {
  return new Response(
    `I am an Vercel Function! (executed on ${process.env.VERCEL_REGION})`,
    {
      status: 200,
    },
  );
}

During regional outage, Vercel has automatic failover to the next closest region to maintain uptime. This is applicable for both global and regionally specified Edge Functions. See the outage resiliency docs for more information.

If you're not using a framework, you must either add "type": "module" to your package.json or change your JavaScript Functions' file extensions from .js to .mjs

In the event of regional downtime, Vercel will automatically reroute traffic to the next closest Edge Network region on all plans. For more information on which regions Vercel routes traffic to, see Outage Resiliency.

You can't configure a maximum duration for functions using the Edge runtime. They can run indefinitely provided they send an initial response within 25 seconds.

You can only configure concurrency for functions using the Node.js runtime. Edge Functions cannot be configured.

The Edge runtime is built on top of the V8 engine, allowing it to run in isolated execution environments that don't require a container or virtual machine.

The Edge runtime provides a subset of Web APIs such as fetch, Request, and Response.

The following tables list the APIs that are available in the Edge runtime.

APIDescription
fetchFetches a resource
RequestRepresents an HTTP request
ResponseRepresents an HTTP response
HeadersRepresents HTTP headers
FormDataRepresents form data
FileRepresents a file
BlobRepresents a blob
URLSearchParamsRepresents URL search parameters
BlobRepresents a blob
EventRepresents an event
EventTargetRepresents an object that can handle events
PromiseRejectEventRepresents an event that is sent to the global scope of a script when a JavaScript Promise is rejected
APIDescription
TextEncoderEncodes a string into a Uint8Array
TextDecoderDecodes a Uint8Array into a string
atobDecodes a base-64 encoded string
btoaEncodes a string in base-64
APIDescription
ReadableStreamRepresents a readable stream
WritableStreamRepresents a writable stream
WritableStreamDefaultWriterRepresents a writer of a WritableStream
TransformStreamRepresents a transform stream
ReadableStreamDefaultReaderRepresents a reader of a ReadableStream
ReadableStreamBYOBReaderRepresents a reader of a ReadableStream
APIDescription
cryptoProvides access to the cryptographic functionality of the platform
SubtleCryptoProvides access to common cryptographic primitives, like hashing, signing, encryption or decryption
CryptoKeyRepresents a cryptographic key
APIDescription
AbortControllerAllows you to abort one or more DOM requests as and when desired
AbortSignalRepresents a signal object that allows you to communicate with a DOM request (such as a Fetch request) and abort it if required
DOMExceptionRepresents an error that occurs in the DOM
structuredCloneCreates a deep copy of a value
URLPatternRepresents a URL pattern
ArrayRepresents an array of values
ArrayBufferRepresents a generic, fixed-length raw binary data buffer
AtomicsProvides atomic operations as static methods
BigIntRepresents a whole number with arbitrary precision
BigInt64ArrayRepresents a typed array of 64-bit signed integers
BigUint64ArrayRepresents a typed array of 64-bit unsigned integers
BooleanRepresents a logical entity and can have two values: true and false
clearIntervalCancels a timed, repeating action which was previously established by a call to setInterval()
clearTimeoutCancels a timed, repeating action which was previously established by a call to setTimeout()
consoleProvides access to the browser's debugging console
DataViewRepresents a generic view of an ArrayBuffer
DateRepresents a single moment in time in a platform-independent format
decodeURIDecodes a Uniform Resource Identifier (URI) previously created by encodeURI or by a similar routine
decodeURIComponentDecodes a Uniform Resource Identifier (URI) component previously created by encodeURIComponent or by a similar routine
encodeURIEncodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character
encodeURIComponentEncodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character
ErrorRepresents an error when trying to execute a statement or accessing a property
EvalErrorRepresents an error that occurs regarding the global function eval()
Float32ArrayRepresents a typed array of 32-bit floating point numbers
Float64ArrayRepresents a typed array of 64-bit floating point numbers
FunctionRepresents a function
InfinityRepresents the mathematical Infinity value
Int8ArrayRepresents a typed array of 8-bit signed integers
Int16ArrayRepresents a typed array of 16-bit signed integers
Int32ArrayRepresents a typed array of 32-bit signed integers
IntlProvides access to internationalization and localization functionality
isFiniteDetermines whether a value is a finite number
isNaNDetermines whether a value is NaN or not
JSONProvides functionality to convert JavaScript values to and from the JSON format
MapRepresents a collection of values, where each value may occur only once
MathProvides access to mathematical functions and constants
NumberRepresents a numeric value
ObjectRepresents the object that is the base of all JavaScript objects
parseFloatParses a string argument and returns a floating point number
parseIntParses a string argument and returns an integer of the specified radix
PromiseRepresents the eventual completion (or failure) of an asynchronous operation, and its resulting value
ProxyRepresents an object that is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc)
RangeErrorRepresents an error when a value is not in the set or range of allowed values
ReferenceErrorRepresents an error when a non-existent variable is referenced
ReflectProvides methods for interceptable JavaScript operations
RegExpRepresents a regular expression, allowing you to match combinations of characters
SetRepresents a collection of values, where each value may occur only once
setIntervalRepeatedly calls a function, with a fixed time delay between each call
setTimeoutCalls a function or evaluates an expression after a specified number of milliseconds
SharedArrayBufferRepresents a generic, fixed-length raw binary data buffer
StringRepresents a sequence of characters
SymbolRepresents a unique and immutable data type that is used as the key of an object property
SyntaxErrorRepresents an error when trying to interpret syntactically invalid code
TypeErrorRepresents an error when a value is not of the expected type
Uint8ArrayRepresents a typed array of 8-bit unsigned integers
Uint8ClampedArrayRepresents a typed array of 8-bit unsigned integers clamped to 0-255
Uint32ArrayRepresents a typed array of 32-bit unsigned integers
URIErrorRepresents an error when a global URI handling function was used in a wrong way
URLRepresents an object providing static methods used for creating object URLs
URLSearchParamsRepresents a collection of key/value pairs
WeakMapRepresents a collection of key/value pairs in which the keys are weakly referenced
WeakSetRepresents a collection of objects in which each object may occur only once
WebAssemblyProvides access to WebAssembly

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
}

The following modules can be imported with and without the node: prefix when using the import statement:

ModuleDescription
async_hooksManage asynchronous resources lifecycles with AsyncLocalStorage. Supports the WinterCG subset of APIs
eventsFacilitate event-driven programming with custom event emitters and listeners. This API is fully supported
bufferEfficiently manipulate binary data using fixed-size, raw memory allocations with Buffer. Every primitive compatible with Uint8Array accepts Buffer too
assertProvide a set of assertion functions for verifying invariants in your code
utilOffer various utility functions where we include promisify/callbackify and types

Also, Buffer is globally exposed to maximize compatibility with existing Node.js modules.

The Edge runtime has some restrictions including:

  • Some Node.js APIs other than the ones listed above 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:

APIDescription
evalEvaluates JavaScript code represented as a string
new Function(evalString)Creates a new function with the code provided as an argument
WebAssembly.compileCompiles a WebAssembly module from a buffer source
WebAssembly.instantiateCompiles and instantiates a WebAssembly module from a buffer source

While WebAssembly.instantiate is supported in Edge Runtime, it requires the Wasm source code to be provided using the import statement. This means you cannot use a buffer or byte array to dynamically compile the module at runtime.

You can use process.env to access Environment Variables.

Middleware with the edge runtime configured is neither a Node.js nor browser application, which means it doesn't have access to all browser and Node.js APIs. Currently, our runtime offers a subset of browser APIs and some Node.js APIs and we plan to implement more functionality in the future.

In summary:

  • Use ES modules
  • Most libraries that use Node.js APIs as dependencies can't be used in Middleware with the edge runtime configured.
  • Dynamic code execution (such as eval) is not allowed (see the next section for more details)

Dynamic code execution is not available in Middleware with the edge runtime configured for security reasons. For example, the following APIs cannot be used:

APIDescription
evalEvaluates JavaScript code represented as a string
new Function(evalString)Creates a new function with the code provided as an argument
WebAssembly.instantiateCompiles and instantiates a WebAssembly module from a buffer source

You need to make sure libraries used in your Middleware with the edge runtime configured don't rely on dynamic code execution because it leads to a runtime error.

Middleware with the edge runtime configured must begin sending a response within 25 seconds.

You may continue streaming a response beyond that time and you can continue with asynchronous workloads in the background, after returning the response.

PlanLimit (after gzip compression)
Hobby1 MB
Pro2 MB
Enterprise4 MB

The maximum size for an Vercel Function using the Edge runtime includes your JavaScript code, imported libraries and files (such as fonts), and all files bundled in the function.

If you reach the limit, make sure the code you are importing in your function is used and is not too heavy. You can use a package size checker tool like bundle to check the size of a package and search for a smaller alternative.

Environment Variables can be accessed through the process.env object. Since JavaScript objects have methods to allow some operations on them, there are limitations on the names of Environment Variables to avoid having ambiguous code.

The following names will be ignored as Environment Variables to avoid overriding the process.env object prototype:

  • constructor
  • __defineGetter__
  • __defineSetter__
  • hasOwnProperty
  • __lookupGetter__
  • __lookupSetter__
  • isPrototypeOf
  • propertyIsEnumerable
  • toString
  • valueOf
  • __proto__
  • toLocaleString

Therefore, your code will always be able to use them with their expected behavior:

// returns `true`, if `process.env.MY_VALUE` is used anywhere & defined in the Vercel dashboard
process.env.hasOwnProperty('MY_VALUE');
Last updated on March 6, 2025