Skip to content

Commit 4688080

Browse files
committed
fix(nextjs): TypeError: res.once is not a function
1 parent 8cbcff2 commit 4688080

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

packages/nextjs/src/utils/instrumentServer.ts

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,11 @@ export interface NextRequest extends http.IncomingMessage {
4141
headers: { [key: string]: string };
4242
body: string | { [key: string]: unknown };
4343
}
44-
type NextResponse = http.ServerResponse;
44+
type NextResponse =
45+
| http.ServerResponse
46+
| {
47+
originalRequest: http.ServerResponse;
48+
};
4549

4650
// the methods we'll wrap
4751
type HandlerGetter = () => Promise<ReqHandler>;
@@ -107,6 +111,21 @@ export function instrumentServer(): void {
107111
fill(nextServerPrototype, 'getServerRequestHandler', makeWrappedHandlerGetter);
108112
}
109113

114+
/**
115+
* Return http.ServerResponse object regardless of Next.js version.
116+
* Since Next.js version 12.0.9, a custom object called NodeNextResponse is used instead of http.ServerResponse.
117+
*
118+
* @param nextRes Next.js's response object
119+
* @returns pure http.ServerResponse object
120+
*/
121+
function convertToHttpSeverResponse(nextRes: NextResponse): http.ServerResponse {
122+
if ('originalRequest' in nextRes) {
123+
return nextRes.originalRequest;
124+
} else {
125+
return nextRes;
126+
}
127+
}
128+
110129
/**
111130
* Create a wrapped version of Nextjs's `NextServer.getServerRequestHandler` method, as a way to access the running
112131
* `Server` instance and monkeypatch its prototype.
@@ -206,9 +225,11 @@ function makeWrappedReqHandler(origReqHandler: ReqHandler): WrappedReqHandler {
206225
const wrappedReqHandler = async function (
207226
this: Server,
208227
req: NextRequest,
209-
res: NextResponse,
228+
nextRes: NextResponse,
210229
parsedUrl?: url.UrlWithParsedQuery,
211230
): Promise<void> {
231+
const res = convertToHttpSeverResponse(nextRes);
232+
212233
// wrap everything in a domain in order to prevent scope bleed between requests
213234
const local = domain.create();
214235
local.add(req);

0 commit comments

Comments
 (0)