Skip to content

Commit e007b08

Browse files
fix: add shim for require('node:buffer') (#2050)
* fix: add buffer require shim * chore: add comment for buffer require shim * feat: shim additional native modules --------- Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent 826d708 commit e007b08

File tree

1 file changed

+27
-3
lines changed
  • packages/runtime/src/templates/edge

1 file changed

+27
-3
lines changed

packages/runtime/src/templates/edge/shims.js

+27-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
// @ts-check
2-
// deno-lint-ignore-file no-var prefer-const no-unused-vars no-explicit-any
2+
// deno-lint-ignore-file prefer-const no-unused-vars
33
import { decode as _base64Decode } from 'https://deno.land/[email protected]/encoding/base64.ts'
4-
import { AsyncLocalStorage as ALSCompat } from 'https://deno.land/[email protected]/node/async_hooks.ts'
4+
import BufferCompat from 'https://deno.land/[email protected]/node/buffer.ts'
5+
import EventsCompat from 'https://deno.land/[email protected]/node/events.ts'
6+
import AsyncHooksCompat from 'https://deno.land/[email protected]/node/async_hooks.ts'
7+
import AssertCompat from 'https://deno.land/[email protected]/node/assert.ts'
8+
import UtilCompat from 'https://deno.land/[email protected]/node/util.ts'
59

610
/**
711
* These are the shims, polyfills and other kludges to make Next.js work in standards-compliant runtime.
@@ -18,7 +22,7 @@ globalThis.EdgeRuntime = 'netlify-edge'
1822
let _ENTRIES = {}
1923

2024
// Next.js expects this as a global
21-
globalThis.AsyncLocalStorage = ALSCompat
25+
globalThis.AsyncLocalStorage = AsyncHooksCompat.AsyncLocalStorage
2226

2327
// Next.js uses this extension to the Headers API implemented by Cloudflare workerd
2428
if (!('getAll' in Headers.prototype)) {
@@ -48,6 +52,26 @@ const fetch /* type {typeof globalThis.fetch} */ = async (url, init) => {
4852
}
4953
}
5054

55+
// Shim native modules that Vercel makes available
56+
if (typeof require === 'undefined') {
57+
globalThis.require = (name) => {
58+
switch (name.replace(/^node:/, '')) {
59+
case 'buffer':
60+
return BufferCompat
61+
case 'events':
62+
return EventsCompat
63+
case 'async_hooks':
64+
return AsyncHooksCompat
65+
case 'assert':
66+
return AssertCompat
67+
case 'util':
68+
return UtilCompat
69+
default:
70+
throw new ReferenceError(`Native module not found: ${name}`)
71+
}
72+
}
73+
}
74+
5175
// Next edge runtime uses "self" as a function-scoped global-like object, but some of the older polyfills expect it to equal globalThis
5276
// See https://nextjs.org/docs/basic-features/supported-browsers-features#polyfills
5377
const self = { ...globalThis, fetch }

0 commit comments

Comments
 (0)