Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/salty-deer-cheat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@module-federation/nextjs-mf': patch
---

Fix server-side onLoad crash when async remote module factories are used during the webpack build/SSR path. Await async factory results before proxy-wrapping, return a wrapper factory for exposeModuleFactory, and preserve class constructor semantics via Proxy apply/construct traps.
178 changes: 178 additions & 0 deletions packages/nextjs-mf/src/plugins/container/runtimePlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,181 @@ describe('next-internal-plugin beforeRequest', () => {
);
});
});

describe('next-internal-plugin onLoad', () => {
const plugin = createRuntimePlugin();
const onLoad = plugin.onLoad!;
const originalWindow = global.window;

describe('server', () => {
beforeEach(() => {
delete global.window;
globalThis.usedChunks = new Set();
});

afterEach(() => {
global.window = originalWindow;
});

it('awaits async exposeModuleFactory on server before proxy-wrapping', async () => {
const moduleExports = { __esModule: true, default: null };
const asyncFactory = async () => moduleExports;

const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: asyncFactory,
exposeModule: undefined,
});

expect(typeof result).toBe('function');
expect(result()).toEqual(
expect.objectContaining({ __esModule: true, default: null }),
);
});

it('returns a wrapper factory for async namespace exports on server', async () => {
const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: async () => ({ __esModule: true, default: null }),
exposeModule: undefined,
});

expect(typeof result).toBe('function');
expect(result()).toEqual(
expect.objectContaining({ __esModule: true, default: null }),
);
});

it('does not break Promise.prototype.then when async factory resolves on server', async () => {
const asyncFactory = async () => ({ __esModule: true, default: null });

const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: asyncFactory,
exposeModule: undefined,
});

expect(typeof result).toBe('function');
expect(() =>
Promise.resolve(result()).then(() => undefined),
).not.toThrow();
});

it('handles sync exposeModuleFactory on server', async () => {
const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: () => ({ __esModule: true, default: null }),
exposeModule: undefined,
});

expect(typeof result).toBe('function');
expect(result()).toEqual(
expect.objectContaining({ __esModule: true, default: null }),
);
});

it('propagates rejected async factory on server', async () => {
await expect(
onLoad({
id: 'remote/expose',
exposeModuleFactory: async () => {
throw new Error('factory failed');
},
exposeModule: undefined,
}),
).rejects.toThrow('factory failed');
});

it('keeps class default export constructible after async factory', async () => {
class RemoteComponent {
tag = 'remote';
}

const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: async () => ({
__esModule: true,
default: RemoteComponent,
}),
exposeModule: undefined,
});

const exports = result();
const instance = new exports.default();

expect(instance).toBeInstanceOf(RemoteComponent);
expect(instance.tag).toBe('remote');
});

it('records usedChunks when class is constructed', async () => {
class RemoteComponent {}

const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: async () => ({
__esModule: true,
default: RemoteComponent,
}),
exposeModule: undefined,
});

const exports = result();
new exports.default();

expect(globalThis.usedChunks.has('remote/expose')).toBe(true);
});

it('preserves static properties on function exports', async () => {
const fn = Object.assign(() => 'ok', {
getServerSideProps: () => ({ props: {} }),
});

const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: async () => ({
__esModule: true,
default: fn,
}),
exposeModule: undefined,
});

const exports = result();
expect(exports.default()).toBe('ok');
expect(exports.default.getServerSideProps()).toEqual({ props: {} });
});

it('keeps plain function default export callable', async () => {
const result = await onLoad({
id: 'remote/expose',
exposeModuleFactory: async () => ({
__esModule: true,
default: () => 'plain-fn',
}),
exposeModule: undefined,
});

const exports = result();
expect(exports.default()).toBe('plain-fn');
});
});

describe('client', () => {
afterEach(() => {
global.window = originalWindow;
});

it('returns args unchanged on the client', async () => {
global.window = originalWindow ?? ({} as Window & typeof globalThis);

const input = {
id: 'remote/expose',
exposeModuleFactory: async () => ({ __esModule: true, default: null }),
exposeModule: undefined,
};

const result = await onLoad(input);

expect(result).toBe(input);
});
});
});
84 changes: 39 additions & 45 deletions packages/nextjs-mf/src/plugins/container/runtimePlugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
import { ModuleFederationRuntimePlugin } from '@module-federation/runtime';
import { matchRemoteWithNameAndExpose } from '@module-federation/runtime-core';

function wrapCallableForChunkTracking<T extends (...args: any[]) => any>(
fn: T,
id: string,
): T {
return new Proxy(fn, {
apply(_target, thisArg, args) {
globalThis.usedChunks.add(id);
return Reflect.apply(fn, thisArg, args);
},
construct(_target, args, newTarget) {
globalThis.usedChunks.add(id);
return Reflect.construct(fn, args, newTarget);
},
get(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
},
});
}

export default function (): ModuleFederationRuntimePlugin {
return {
name: 'next-internal-plugin',
Expand Down Expand Up @@ -113,7 +132,7 @@ export default function (): ModuleFederationRuntimePlugin {
afterResolve: function (args: any) {
return args;
},
onLoad: function (args: any) {
onLoad: async function (args: any) {
const exposeModuleFactory = args.exposeModuleFactory;
const exposeModule = args.exposeModule;
const id = args.id;
Expand All @@ -128,60 +147,35 @@ export default function (): ModuleFederationRuntimePlugin {
exposedModuleExports = moduleOrFactory;
}

exposedModuleExports = await exposedModuleExports;

const handler: ProxyHandler<any> = {
get: function (target, prop, receiver) {
if (
target === exposedModuleExports &&
typeof exposedModuleExports[prop] === 'function'
) {
return function (this: unknown) {
globalThis.usedChunks.add(id);
//eslint-disable-next-line
return exposedModuleExports[prop].apply(this, arguments);
};
}

const originalMethod = target[prop];
if (typeof originalMethod === 'function') {
const proxiedFunction = function (this: unknown) {
globalThis.usedChunks.add(id);
//eslint-disable-next-line
return originalMethod.apply(this, arguments);
};

Object.keys(originalMethod).forEach(function (prop) {
Object.defineProperty(proxiedFunction, prop, {
value: originalMethod[prop],
writable: true,
enumerable: true,
configurable: true,
});
});

return proxiedFunction;
const value = Reflect.get(target, prop, receiver);
if (typeof value === 'function') {
return wrapCallableForChunkTracking(value, id);
}

return Reflect.get(target, prop, receiver);
return value;
},
};

if (typeof exposedModuleExports === 'function') {
exposedModuleExports = new Proxy(exposedModuleExports, handler);

const staticProps = Object.getOwnPropertyNames(exposedModuleExports);
staticProps.forEach(function (prop) {
if (typeof exposedModuleExports[prop] === 'function') {
exposedModuleExports[prop] = new Proxy(
exposedModuleExports[prop],
handler,
);
}
});
exposedModuleExports = wrapCallableForChunkTracking(
exposedModuleExports,
id,
);
return function () {
return exposedModuleExports;
};
} else {
exposedModuleExports = new Proxy(exposedModuleExports, handler);
}

exposedModuleExports = new Proxy(exposedModuleExports, handler);

if (exposeModuleFactory) {
const wrappedExports = exposedModuleExports;
return function () {
return wrappedExports;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Returning wrappedExports as the module factory makes the namespace proxy observable to webpack. The proxy's get trap currently replaces every function export with a plain wrapper that
invokes originalMethod.apply(...), which does not preserve constructor/class semantics.

For example, an async factory resolving to:

{ default: class RemoteComponent {} }

now produces an export where new exports.default() throws:

TypeError: Class constructor RemoteComponent cannot be invoked without 'new'

This can break default-exported React class components and other constructible exports during SSR/build. Could we preserve both call and construct behavior, for example by proxying exported
functions with apply and construct traps using Reflect.apply/Reflect.construct? Please also add a regression test verifying that a class returned by an async factory remains
constructible and preserves instanceof.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in e7e1e0f replaced the .apply()-based wrapper with wrapCallableForChunkTracking, a Proxy using apply/construct traps (Reflect.apply/Reflect.construct), so constructible exports work through the proxy on the server.

Added the regression test you asked for: keeps class default export constructible after async factory, asserting new exports.default() + instanceof both hold. Also covered usedChunks tracking on construction and static-prop/plain-function cases.

Note: static methods on the wrapped default (exports.default.someStatic()) aren't individually tracked anymore, only top-level apply/construct marks usedChunks. Since tracking is at remote/expose granularity, not per-method, this shouldn't matter in practice, but flag if you'd want it covered explicitly.

};
}

return exposedModuleExports;
Expand Down