Capítulo 444 de 456

Edge Runtime

Core Idea

API reference for the Edge Runtime, Next.js's limited server runtime (used in Proxy) versus the default Node.js Runtime. Supports a Web Standard-aligned API surface, but not Node.js APIs or ISR.

Key Concepts

  • Two runtimes: Node.js Runtime (default, full Node.js API access, used for rendering) vs. Edge Runtime (limited API set, used in Proxy).
  • Caveats: Edge doesn't support all Node.js APIs or ISR; both runtimes can stream depending on the deployment adapter.
  • Supported categories: Network APIs (fetch, Request, Response, Headers, WebSocket, ...), Encoding APIs (TextEncoder, atob/btoa, ...), Stream APIs (ReadableStream, TransformStream, ...), Crypto APIs (crypto, SubtleCrypto, CryptoKey), and a broad set of Web Standard globals (Array, Promise, URL, URLPattern, structuredClone, etc.).
  • Next.js-specific polyfill: AsyncLocalStorage.
  • process.env: available in both next dev and next build on Edge.
  • Unsupported: native Node.js APIs (no filesystem access), direct require() (use ES Modules), eval, new Function(evalString), WebAssembly.compile/instantiate.
  • unstable_allowDynamic: glob(s) in Proxy config to allow specific files containing unreachable dynamic-code-eval statements that can't be tree-shaken.

Code Examples

export const config = {
  unstable_allowDynamic: [
    '/lib/utilities.js',
    '**/node_modules/function-bind/**',
  ],
}
  • O que demonstra: relaxa o check de dynamic code evaluation pra arquivos/globs específicos que não podem ser alcançados em runtime.

Reference Tables

Categorias de API suportadas: Network (Blob, fetch, FetchEvent, File, FormData, Headers, Request, Response, URLSearchParams, WebSocket), Encoding (atob, btoa, TextDecoder(Stream), TextEncoder(Stream)), Stream (ReadableStream(BYOBReader/DefaultReader), TransformStream, WritableStream(DefaultWriter)), Crypto (crypto, CryptoKey, SubtleCrypto), Web Standard (globals JS padrão: Array, Date, JSON, Map, Set, Promise, Proxy, RegExp, URL, URLPattern, WeakMap/WeakSet, WebAssembly, timers, erros, etc.)

Anti-patterns

  • Chamar require() diretamente no Edge Runtime: não é permitido; use ES Modules.
  • Usar pacotes de node_modules que dependem de APIs nativas do Node: só funcionam se implementarem ES Modules puros sem APIs nativas.
  • Usar eval/new Function/WebAssembly.compile/instantiate no Edge: desabilitados, lançam erro em runtime se executados.

Key Takeaways

  1. Edge Runtime é um subconjunto Web Standard, não Node.js completo, pensado pra rodar em Proxy.
  2. ISR não é suportado no Edge Runtime.
  3. unstable_allowDynamic é uma válvula de escape pra código dinâmico inalcançável que o tree-shaking não consegue remover, mas não protege contra execução real (isso ainda quebra em runtime).

Connects To

  • Invoking Entrypoints (ch440): como a runtime Edge é efetivamente invocada via output.edgeRuntime.
  • Proxy (file convention): local onde unstable_allowDynamic e o Edge Runtime são configurados.