Skip to content

Commit 95951ac

Browse files
Make sure next-on-pages can work with Next 15.2 (#960)
* fix Next.js re-defining global `__import_unsupported` * fix `AbortController`s being created in the global scope
1 parent 181fad6 commit 95951ac

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

.changeset/healthy-beans-heal.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@cloudflare/next-on-pages': patch
3+
---
4+
5+
fix Next.js re-defining global `__import_unsupported`

.changeset/rich-dogs-push.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@cloudflare/next-on-pages': patch
3+
---
4+
5+
fix `AbortController`s being created in the global scope

packages/next-on-pages/templates/_worker.js/index.ts

+60
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,66 @@ declare const __ALSes_PROMISE__: Promise<null | {
2121
requestContextAsyncLocalStorage: AsyncLocalStorage<unknown>;
2222
}>;
2323

24+
const originalDefineProperty = Object.defineProperty;
25+
26+
const patchedDefineProperty = (
27+
...args: Parameters<typeof Object.defineProperty<unknown>>
28+
) => {
29+
const target = args[0];
30+
const key = args[1];
31+
// Next.js defined an __import_unsupported global property as non configurable
32+
// with next-on-pages this apps try to re-define this property multiple times,
33+
// so here we patch `defineProperty` to just ignore re-definition of such property
34+
const importUnsupportedKey = '__import_unsupported';
35+
if (key === importUnsupportedKey) {
36+
if (
37+
typeof target === 'object' &&
38+
target !== null &&
39+
importUnsupportedKey in target
40+
) {
41+
return;
42+
}
43+
}
44+
return originalDefineProperty(...args);
45+
};
46+
47+
global.Object.defineProperty =
48+
patchedDefineProperty as typeof global.Object.defineProperty;
49+
50+
global.AbortController = class PatchedAbortController extends AbortController {
51+
constructor() {
52+
try {
53+
super();
54+
} catch (e) {
55+
if (
56+
e instanceof Error &&
57+
e.message.includes('Disallowed operation called within global scope')
58+
) {
59+
// Next.js attempted to create an AbortController in the global scope
60+
// let's return something that looks like an AbortController but with
61+
// noop functionalities
62+
return {
63+
signal: {
64+
aborted: false,
65+
reason: null,
66+
onabort: () => {
67+
/* empty */
68+
},
69+
throwIfAborted: () => {
70+
/* empty */
71+
},
72+
} as unknown as AbortSignal,
73+
abort() {
74+
/* empty */
75+
},
76+
};
77+
} else {
78+
throw e;
79+
}
80+
}
81+
}
82+
};
83+
2484
export default {
2585
async fetch(request, env, ctx) {
2686
setupRoutesIsolation();

0 commit comments

Comments
 (0)