-
Notifications
You must be signed in to change notification settings - Fork 28k
/
Copy pathsend-response.ts
59 lines (53 loc) · 1.89 KB
/
send-response.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import { isNodeNextResponse } from './base-http/helpers'
import { pipeToNodeResponse } from './pipe-readable'
import { splitCookiesString } from './web/utils'
/**
* Sends the response on the underlying next response object.
*
* @param req the underlying request object
* @param res the underlying response object
* @param response the response to send
*/
export async function sendResponse(
req: BaseNextRequest,
res: BaseNextResponse,
response: Response,
waitUntil?: Promise<unknown>
): Promise<void> {
if (
// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextResponse(res)
) {
// Copy over the response status.
res.statusCode = response.status
res.statusMessage = response.statusText
// Copy over the response headers.
response.headers?.forEach((value, name) => {
// The append handling is special cased for `set-cookie`.
if (name.toLowerCase() === 'set-cookie') {
// TODO: (wyattjoh) replace with native response iteration when we can upgrade undici
for (const cookie of splitCookiesString(value)) {
res.appendHeader(name, cookie)
}
} else {
res.appendHeader(name, value)
}
})
/**
* The response can't be directly piped to the underlying response. The
* following is duplicated from the edge runtime handler.
*
* See packages/next/server/next-server.ts
*/
const { originalResponse } = res
// A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD
if (response.body && req.method !== 'HEAD') {
await pipeToNodeResponse(response.body, originalResponse, waitUntil)
} else {
originalResponse.end()
}
}
}