Unverified Commit d5685504 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

refactor: encapsulate content type within RenderResult (#81861)

### Problem
The PPR boundary sentinel was being incorrectly added to responses due
to flawed content type logic in `sendRenderResult`. The original
conditional logic had complex fallbacks that caused the sentinel to be
added when it shouldn't be:

```javascript
// BEFORE: Incorrect logic - sentinel added to wrong response types
if (
  process.env.__NEXT_TEST_MODE &&
  minimalMode &&
  isRoutePPREnabled &&
  // ❌ This logic was inverted and unreliable
  body.contentType !== RSC_CONTENT_TYPE_HEADER &&
  !isRSCRequest
) {
  body.unshift(createPPRBoundarySentinel())
}
```

The problem was that `body.contentType` was inconsistently determined
through external logic in `sendRenderResult`, causing the sentinel to
appear in responses that shouldn't have it.

### Solution
By moving content type into `RenderResult` constructor, the sentinel
logic now correctly identifies HTML responses:

```javascript
// AFTER: Correct logic - sentinel only added to HTML responses
if (
  process.env.__NEXT_TEST_MODE &&
  minimalMode &&
  isRoutePPREnabled &&
  body.contentType === HTML_CONTENT_TYPE_HEADER // ✅ Reliable content type check
) {
  body.unshift(createPPRBoundarySentinel())
}
```

### Key Changes
- **Fixed sentinel logic**: PPR boundary sentinel now only appears in
HTML responses where it belongs
- **Reliable content type**: Content type is determined at RenderResult
creation, not through fallback logic
- **Consistent API**: Removed redundant `type` parameter that was
causing the confusion

This ensures PPR test assertions work correctly by only adding the
boundary sentinel to the appropriate response types.
parent 8c94014b
...@@ -728,5 +728,8 @@ ...@@ -728,5 +728,8 @@
"727": "Route %s couldn't be rendered statically because it used IO that was not cached. See more info here: https://nextjs.org/docs/messages/cache-components", "727": "Route %s couldn't be rendered statically because it used IO that was not cached. See more info here: https://nextjs.org/docs/messages/cache-components",
"728": "CacheSignal cannot be used in the edge runtime, because `cacheComponents` does not support it.", "728": "CacheSignal cannot be used in the edge runtime, because `cacheComponents` does not support it.",
"729": "\\`experimental.ppr\\` can not be \\`%s\\` when \\`experimental.cacheComponents\\` is \\`true\\`. PPR is implicitly enabled when Cache Components is enabled.", "729": "\\`experimental.ppr\\` can not be \\`%s\\` when \\`experimental.cacheComponents\\` is \\`true\\`. PPR is implicitly enabled when Cache Components is enabled.",
"730": "Dynamic imports should not be instrumented in the edge runtime, because `cacheComponents` doesn't support it" "730": "Dynamic imports should not be instrumented in the edge runtime, because `cacheComponents` doesn't support it",
"731": "chainStreams requires at least one stream",
"732": "dynamic responses cannot be unchunked. This is a bug in Next.js",
"733": "null responses cannot be unchunked"
} }
...@@ -44,7 +44,11 @@ import { ...@@ -44,7 +44,11 @@ import {
} from '../../server/response-cache' } from '../../server/response-cache'
import { FallbackMode, parseFallbackField } from '../../lib/fallback' import { FallbackMode, parseFallbackField } from '../../lib/fallback'
import RenderResult from '../../server/render-result' import RenderResult from '../../server/render-result'
import { CACHE_ONE_YEAR, NEXT_CACHE_TAGS_HEADER } from '../../lib/constants' import {
CACHE_ONE_YEAR,
HTML_CONTENT_TYPE_HEADER,
NEXT_CACHE_TAGS_HEADER,
} from '../../lib/constants'
import type { CacheControl } from '../../server/lib/cache-control' import type { CacheControl } from '../../server/lib/cache-control'
import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags' import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags'
import { sendRenderResult } from '../../server/send-payload' import { sendRenderResult } from '../../server/send-payload'
...@@ -728,7 +732,7 @@ export async function handler( ...@@ -728,7 +732,7 @@ export async function handler(
cacheControl: { revalidate: 1, expire: undefined }, cacheControl: { revalidate: 1, expire: undefined },
value: { value: {
kind: CachedRouteKind.PAGES, kind: CachedRouteKind.PAGES,
html: RenderResult.fromStatic(''), html: RenderResult.EMPTY,
pageData: {}, pageData: {},
headers: undefined, headers: undefined,
status: undefined, status: undefined,
...@@ -917,10 +921,12 @@ export async function handler( ...@@ -917,10 +921,12 @@ export async function handler(
return sendRenderResult({ return sendRenderResult({
req, req,
res, res,
type: 'rsc',
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(matchedSegment), result: RenderResult.fromStatic(
matchedSegment,
RSC_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
}) })
} }
...@@ -935,10 +941,9 @@ export async function handler( ...@@ -935,10 +941,9 @@ export async function handler(
return sendRenderResult({ return sendRenderResult({
req, req,
res, res,
type: 'rsc',
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(''), result: RenderResult.EMPTY,
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
}) })
} }
...@@ -1041,7 +1046,6 @@ export async function handler( ...@@ -1041,7 +1046,6 @@ export async function handler(
return sendRenderResult({ return sendRenderResult({
req, req,
res, res,
type: 'rsc',
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: cachedData.html, result: cachedData.html,
...@@ -1061,10 +1065,12 @@ export async function handler( ...@@ -1061,10 +1065,12 @@ export async function handler(
return sendRenderResult({ return sendRenderResult({
req, req,
res, res,
type: 'rsc',
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(cachedData.rscData), result: RenderResult.fromStatic(
cachedData.rscData,
RSC_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
}) })
} }
...@@ -1083,10 +1089,7 @@ export async function handler( ...@@ -1083,10 +1089,7 @@ export async function handler(
process.env.__NEXT_TEST_MODE && process.env.__NEXT_TEST_MODE &&
minimalMode && minimalMode &&
isRoutePPREnabled && isRoutePPREnabled &&
// If the response body is an RSC content type of the request was for body.contentType === HTML_CONTENT_TYPE_HEADER
// an RSC request then we shouldn't add the sentinel.
body.contentType !== RSC_CONTENT_TYPE_HEADER &&
!isRSCRequest
) { ) {
// As we're in minimal mode, the static part would have already been // As we're in minimal mode, the static part would have already been
// streamed first. The only part that this streams is the dynamic part // streamed first. The only part that this streams is the dynamic part
...@@ -1097,7 +1100,6 @@ export async function handler( ...@@ -1097,7 +1100,6 @@ export async function handler(
return sendRenderResult({ return sendRenderResult({
req, req,
res, res,
type: isRSCRequest ? 'rsc' : 'html',
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: body, result: body,
...@@ -1124,7 +1126,6 @@ export async function handler( ...@@ -1124,7 +1126,6 @@ export async function handler(
return sendRenderResult({ return sendRenderResult({
req, req,
res, res,
type: 'html',
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: body, result: body,
...@@ -1180,7 +1181,6 @@ export async function handler( ...@@ -1180,7 +1181,6 @@ export async function handler(
return sendRenderResult({ return sendRenderResult({
req, req,
res, res,
type: 'html',
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
result: body, result: body,
......
...@@ -28,6 +28,7 @@ import type RenderResult from '../../server/render-result' ...@@ -28,6 +28,7 @@ import type RenderResult from '../../server/render-result'
import type { RenderResultMetadata } from '../../server/render-result' import type { RenderResultMetadata } from '../../server/render-result'
import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer' import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer'
import { BaseServerSpan } from '../../server/lib/trace/constants' import { BaseServerSpan } from '../../server/lib/trace/constants'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
// injected by the loader afterwards. // injected by the loader afterwards.
declare const nextConfig: NextConfigComplete declare const nextConfig: NextConfigComplete
...@@ -195,7 +196,7 @@ async function requestHandler( ...@@ -195,7 +196,7 @@ async function requestHandler(
const headers = new Headers() const headers = new Headers()
// Set content type // Set content type
const contentType = result.contentType || 'text/html; charset=utf-8' const contentType = result.contentType || HTML_CONTENT_TYPE_HEADER
headers.set('Content-Type', contentType) headers.set('Content-Type', contentType)
// Add metadata headers // Add metadata headers
......
...@@ -31,7 +31,11 @@ import { ...@@ -31,7 +31,11 @@ import {
} from '../../server/lib/cache-control' } from '../../server/lib/cache-control'
import { normalizeRepeatedSlashes } from '../../shared/lib/utils' import { normalizeRepeatedSlashes } from '../../shared/lib/utils'
import { getRedirectStatus } from '../../lib/redirect-status' import { getRedirectStatus } from '../../lib/redirect-status'
import { CACHE_ONE_YEAR } from '../../lib/constants' import {
CACHE_ONE_YEAR,
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
} from '../../lib/constants'
import { sendRenderResult } from '../../server/send-payload' import { sendRenderResult } from '../../server/send-payload'
import RenderResult from '../../server/render-result' import RenderResult from '../../server/render-result'
import { toResponseCacheEntry } from '../../server/response-cache/utils' import { toResponseCacheEntry } from '../../server/response-cache/utils'
...@@ -526,7 +530,7 @@ export async function handler( ...@@ -526,7 +530,7 @@ export async function handler(
html: new RenderResult( html: new RenderResult(
Buffer.from(previousCacheEntry.value.html), Buffer.from(previousCacheEntry.value.html),
{ {
contentType: 'text/html;utf-8', contentType: HTML_CONTENT_TYPE_HEADER,
metadata: { metadata: {
statusCode: previousCacheEntry.value.status, statusCode: previousCacheEntry.value.status,
headers: previousCacheEntry.value.headers, headers: previousCacheEntry.value.headers,
...@@ -653,7 +657,7 @@ export async function handler( ...@@ -653,7 +657,7 @@ export async function handler(
if (result.value.kind === CachedRouteKind.REDIRECT) { if (result.value.kind === CachedRouteKind.REDIRECT) {
if (isNextDataRequest) { if (isNextDataRequest) {
res.setHeader('content-type', 'application/json') res.setHeader('content-type', JSON_CONTENT_TYPE_HEADER)
res.end(JSON.stringify(result.value.props)) res.end(JSON.stringify(result.value.props))
return return
} else { } else {
...@@ -732,7 +736,7 @@ export async function handler( ...@@ -732,7 +736,7 @@ export async function handler(
? new RenderResult( ? new RenderResult(
Buffer.from(JSON.stringify(result.value.pageData)), Buffer.from(JSON.stringify(result.value.pageData)),
{ {
contentType: 'application/json', contentType: JSON_CONTENT_TYPE_HEADER,
metadata: result.value.html.metadata, metadata: result.value.html.metadata,
} }
) )
...@@ -740,7 +744,6 @@ export async function handler( ...@@ -740,7 +744,6 @@ export async function handler(
generateEtags: nextConfig.generateEtags, generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader, poweredByHeader: nextConfig.poweredByHeader,
cacheControl: routeModule.isDev ? undefined : cacheControl, cacheControl: routeModule.isDev ? undefined : cacheControl,
type: isNextDataRequest ? 'json' : 'html',
}) })
} }
......
...@@ -17,6 +17,7 @@ import type { ...@@ -17,6 +17,7 @@ import type {
} from '../../server/lib/mock-request' } from '../../server/lib/mock-request'
import { isInAmpMode } from '../../shared/lib/amp-mode' import { isInAmpMode } from '../../shared/lib/amp-mode'
import { import {
HTML_CONTENT_TYPE_HEADER,
NEXT_DATA_SUFFIX, NEXT_DATA_SUFFIX,
SERVER_PROPS_EXPORT_ERROR, SERVER_PROPS_EXPORT_ERROR,
} from '../../lib/constants' } from '../../lib/constants'
...@@ -96,7 +97,10 @@ export async function exportPagesPage( ...@@ -96,7 +97,10 @@ export async function exportPagesPage(
let renderResult: RenderResult | undefined let renderResult: RenderResult | undefined
if (typeof components.Component === 'string') { if (typeof components.Component === 'string') {
renderResult = RenderResult.fromStatic(components.Component) renderResult = RenderResult.fromStatic(
components.Component,
HTML_CONTENT_TYPE_HEADER
)
if (hasOrigQueryValues) { if (hasOrigQueryValues) {
throw new Error( throw new Error(
......
import type { ServerRuntime } from '../types' import type { ServerRuntime } from '../types'
export const TEXT_PLAIN_CONTENT_TYPE_HEADER = 'text/plain'
export const HTML_CONTENT_TYPE_HEADER = 'text/html; charset=utf-8'
export const JSON_CONTENT_TYPE_HEADER = 'application/json; charset=utf-8'
export const NEXT_QUERY_PARAM_PREFIX = 'nxtP' export const NEXT_QUERY_PARAM_PREFIX = 'nxtP'
export const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI' export const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'
......
...@@ -24,6 +24,7 @@ import { ...@@ -24,6 +24,7 @@ import {
} from './../index' } from './../index'
import { getCookieParser } from './../get-cookie-parser' import { getCookieParser } from './../get-cookie-parser'
import { import {
JSON_CONTENT_TYPE_HEADER,
PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_HEADER,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
} from '../../../lib/constants' } from '../../../lib/constants'
...@@ -106,7 +107,7 @@ function sendData(req: NextApiRequest, res: NextApiResponse, body: any): void { ...@@ -106,7 +107,7 @@ function sendData(req: NextApiRequest, res: NextApiResponse, body: any): void {
} }
if (isJSONLike) { if (isJSONLike) {
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
} }
res.setHeader('Content-Length', Buffer.byteLength(stringifiedBody)) res.setHeader('Content-Length', Buffer.byteLength(stringifiedBody))
...@@ -120,7 +121,7 @@ function sendData(req: NextApiRequest, res: NextApiResponse, body: any): void { ...@@ -120,7 +121,7 @@ function sendData(req: NextApiRequest, res: NextApiResponse, body: any): void {
*/ */
function sendJson(res: NextApiResponse, jsonBody: any): void { function sendJson(res: NextApiResponse, jsonBody: any): void {
// Set header to application/json // Set header to application/json
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
// Use send to handle request // Use send to handle request
res.send(JSON.stringify(jsonBody)) res.send(JSON.stringify(jsonBody))
......
...@@ -39,6 +39,7 @@ import { ...@@ -39,6 +39,7 @@ import {
import { getModifiedCookieValues } from '../web/spec-extension/adapters/request-cookies' import { getModifiedCookieValues } from '../web/spec-extension/adapters/request-cookies'
import { import {
JSON_CONTENT_TYPE_HEADER,
NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATED_TAGS_HEADER,
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
} from '../../lib/constants' } from '../../lib/constants'
...@@ -247,7 +248,7 @@ async function createForwardedActionResponse( ...@@ -247,7 +248,7 @@ async function createForwardedActionResponse(
console.error(`failed to forward action response`, err) console.error(`failed to forward action response`, err)
} }
return RenderResult.fromStatic('{}') return RenderResult.fromStatic('{}', JSON_CONTENT_TYPE_HEADER)
} }
/** /**
...@@ -389,7 +390,7 @@ async function createRedirectRenderResult( ...@@ -389,7 +390,7 @@ async function createRedirectRenderResult(
} }
} }
return RenderResult.fromStatic('') return RenderResult.EMPTY
} }
// Used to compare Host header and Origin header. // Used to compare Host header and Origin header.
...@@ -655,7 +656,7 @@ export async function handleAction({ ...@@ -655,7 +656,7 @@ export async function handleAction({
res.statusCode = 404 res.statusCode = 404
return { return {
type: 'done', type: 'done',
result: RenderResult.fromStatic('Server action not found.'), result: RenderResult.fromStatic('Server action not found.', 'text/plain'),
} }
} }
...@@ -1060,7 +1061,7 @@ export async function handleAction({ ...@@ -1060,7 +1061,7 @@ export async function handleAction({
res.setHeader('Location', redirectUrl) res.setHeader('Location', redirectUrl)
return { return {
type: 'done', type: 'done',
result: RenderResult.fromStatic(''), result: RenderResult.EMPTY,
} }
} else if (isHTTPAccessFallbackError(err)) { } else if (isHTTPAccessFallbackError(err)) {
res.statusCode = getAccessFallbackHTTPStatus(err) res.statusCode = getAccessFallbackHTTPStatus(err)
......
...@@ -173,7 +173,7 @@ import { CacheSignal } from './cache-signal' ...@@ -173,7 +173,7 @@ import { CacheSignal } from './cache-signal'
import { getTracedMetadata } from '../lib/trace/utils' import { getTracedMetadata } from '../lib/trace/utils'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { INFINITE_CACHE } from '../../lib/constants' import { HTML_CONTENT_TYPE_HEADER, INFINITE_CACHE } from '../../lib/constants'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts' import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
import { parseLoaderTree } from './parse-loader-tree' import { parseLoaderTree } from './parse-loader-tree'
import { import {
...@@ -1476,6 +1476,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1476,6 +1476,7 @@ async function renderToHTMLOrFlightImpl(
const options: RenderResultOptions = { const options: RenderResultOptions = {
metadata, metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
} }
// If we have pending revalidates, wait until they are all resolved. // If we have pending revalidates, wait until they are all resolved.
if ( if (
...@@ -1624,7 +1625,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -1624,7 +1625,10 @@ async function renderToHTMLOrFlightImpl(
metadata metadata
) )
return new RenderResult(stream, { metadata }) return new RenderResult(stream, {
metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
})
} else if (actionRequestResult.type === 'done') { } else if (actionRequestResult.type === 'done') {
if (actionRequestResult.result) { if (actionRequestResult.result) {
actionRequestResult.result.assignMetadata(metadata) actionRequestResult.result.assignMetadata(metadata)
...@@ -1638,6 +1642,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1638,6 +1642,7 @@ async function renderToHTMLOrFlightImpl(
const options: RenderResultOptions = { const options: RenderResultOptions = {
metadata, metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
} }
const stream = await renderToStreamWithTracing( const stream = await renderToStreamWithTracing(
......
...@@ -105,6 +105,7 @@ import { ...@@ -105,6 +105,7 @@ import {
NEXT_URL, NEXT_URL,
NEXT_ROUTER_STATE_TREE_HEADER, NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_IS_PRERENDER_HEADER, NEXT_IS_PRERENDER_HEADER,
RSC_CONTENT_TYPE_HEADER,
} from '../client/components/app-router-headers' } from '../client/components/app-router-headers'
import type { import type {
MatchOptions, MatchOptions,
...@@ -124,6 +125,8 @@ import { sendResponse } from './send-response' ...@@ -124,6 +125,8 @@ import { sendResponse } from './send-response'
import { normalizeNextQueryParam } from './web/utils' import { normalizeNextQueryParam } from './web/utils'
import { import {
CACHE_ONE_YEAR, CACHE_ONE_YEAR,
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
MATCHED_PATH_HEADER, MATCHED_PATH_HEADER,
NEXT_CACHE_TAGS_HEADER, NEXT_CACHE_TAGS_HEADER,
NEXT_RESUME_HEADER, NEXT_RESUME_HEADER,
...@@ -314,7 +317,6 @@ export class WrappedBuildError extends Error { ...@@ -314,7 +317,6 @@ export class WrappedBuildError extends Error {
} }
type ResponsePayload = { type ResponsePayload = {
type: 'html' | 'json' | 'rsc'
body: RenderResult body: RenderResult
cacheControl?: CacheControl cacheControl?: CacheControl
} }
...@@ -391,7 +393,6 @@ export default abstract class Server< ...@@ -391,7 +393,6 @@ export default abstract class Server<
res: ServerResponse, res: ServerResponse,
options: { options: {
result: RenderResult result: RenderResult
type: 'html' | 'json' | 'rsc'
generateEtags: boolean generateEtags: boolean
poweredByHeader: boolean poweredByHeader: boolean
cacheControl: CacheControl | undefined cacheControl: CacheControl | undefined
...@@ -1807,7 +1808,7 @@ export default abstract class Server< ...@@ -1807,7 +1808,7 @@ export default abstract class Server<
} }
const { req, res } = ctx const { req, res } = ctx
const originalStatus = res.statusCode const originalStatus = res.statusCode
const { body, type } = payload const { body } = payload
let { cacheControl } = payload let { cacheControl } = payload
if (!res.sent) { if (!res.sent) {
const { generateEtags, poweredByHeader, dev } = this.renderOpts const { generateEtags, poweredByHeader, dev } = this.renderOpts
...@@ -1824,7 +1825,6 @@ export default abstract class Server< ...@@ -1824,7 +1825,6 @@ export default abstract class Server<
await this.sendRenderResult(req, res, { await this.sendRenderResult(req, res, {
result: body, result: body,
type,
generateEtags, generateEtags,
poweredByHeader, poweredByHeader,
cacheControl, cacheControl,
...@@ -2328,9 +2328,10 @@ export default abstract class Server< ...@@ -2328,9 +2328,10 @@ export default abstract class Server<
// handle static page // handle static page
if (typeof components.Component === 'string') { if (typeof components.Component === 'string') {
return { return {
type: 'html', body: RenderResult.fromStatic(
// TODO: Static pages should be serialized as RenderResult components.Component,
body: RenderResult.fromStatic(components.Component), HTML_CONTENT_TYPE_HEADER
),
} }
} }
...@@ -3125,7 +3126,7 @@ export default abstract class Server< ...@@ -3125,7 +3126,7 @@ export default abstract class Server<
cacheControl: { revalidate: 1, expire: undefined }, cacheControl: { revalidate: 1, expire: undefined },
value: { value: {
kind: CachedRouteKind.PAGES, kind: CachedRouteKind.PAGES,
html: RenderResult.fromStatic(''), html: RenderResult.EMPTY,
pageData: {}, pageData: {},
headers: undefined, headers: undefined,
status: undefined, status: undefined,
...@@ -3361,8 +3362,10 @@ export default abstract class Server< ...@@ -3361,8 +3362,10 @@ export default abstract class Server<
if (matchedSegment !== undefined) { if (matchedSegment !== undefined) {
// Cache hit // Cache hit
return { return {
type: 'rsc', body: RenderResult.fromStatic(
body: RenderResult.fromStatic(matchedSegment), matchedSegment,
RSC_CONTENT_TYPE_HEADER
),
// TODO: Eventually this should use cache control of the individual // TODO: Eventually this should use cache control of the individual
// segment, not the whole page. // segment, not the whole page.
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
...@@ -3377,8 +3380,7 @@ export default abstract class Server< ...@@ -3377,8 +3380,7 @@ export default abstract class Server<
// issued as part of a prefetch. // issued as part of a prefetch.
res.statusCode = 204 res.statusCode = 204
return { return {
type: 'rsc', body: RenderResult.EMPTY,
body: RenderResult.fromStatic(''),
cacheControl: cacheEntry?.cacheControl, cacheControl: cacheEntry?.cacheControl,
} }
} }
...@@ -3452,10 +3454,9 @@ export default abstract class Server< ...@@ -3452,10 +3454,9 @@ export default abstract class Server<
if (isNextDataRequest) { if (isNextDataRequest) {
return { return {
type: 'json',
body: RenderResult.fromStatic( body: RenderResult.fromStatic(
// @TODO: Handle flight data. JSON.stringify(cachedData.props),
JSON.stringify(cachedData.props) JSON_CONTENT_TYPE_HEADER
), ),
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
} }
...@@ -3539,7 +3540,6 @@ export default abstract class Server< ...@@ -3539,7 +3540,6 @@ export default abstract class Server<
} }
return { return {
type: 'rsc',
body: cachedData.html, body: cachedData.html,
// Dynamic RSC responses cannot be cached, even if they're // Dynamic RSC responses cannot be cached, even if they're
// configured with `force-static` because we have no way of // configured with `force-static` because we have no way of
...@@ -3555,8 +3555,10 @@ export default abstract class Server< ...@@ -3555,8 +3555,10 @@ export default abstract class Server<
// As this isn't a prefetch request, we should serve the static flight // As this isn't a prefetch request, we should serve the static flight
// data. // data.
return { return {
type: 'rsc', body: RenderResult.fromStatic(
body: RenderResult.fromStatic(cachedData.rscData), cachedData.rscData,
RSC_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
} }
} }
...@@ -3569,7 +3571,6 @@ export default abstract class Server< ...@@ -3569,7 +3571,6 @@ export default abstract class Server<
// as a server render (rather than a static render). // as a server render (rather than a static render).
if (!didPostpone || this.minimalMode) { if (!didPostpone || this.minimalMode) {
return { return {
type: 'html',
body, body,
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
} }
...@@ -3592,7 +3593,6 @@ export default abstract class Server< ...@@ -3592,7 +3593,6 @@ export default abstract class Server<
) )
return { return {
type: 'html',
body, body,
cacheControl: { revalidate: 0, expire: undefined }, cacheControl: { revalidate: 0, expire: undefined },
} }
...@@ -3637,7 +3637,6 @@ export default abstract class Server< ...@@ -3637,7 +3637,6 @@ export default abstract class Server<
}) })
return { return {
type: 'html',
body, body,
// We don't want to cache the response if it has postponed data because // We don't want to cache the response if it has postponed data because
// the response being sent to the client it's dynamic parts are streamed // the response being sent to the client it's dynamic parts are streamed
...@@ -3646,13 +3645,14 @@ export default abstract class Server< ...@@ -3646,13 +3645,14 @@ export default abstract class Server<
} }
} else if (isNextDataRequest) { } else if (isNextDataRequest) {
return { return {
type: 'json', body: RenderResult.fromStatic(
body: RenderResult.fromStatic(JSON.stringify(cachedData.pageData)), JSON.stringify(cachedData.pageData),
JSON_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
} }
} else { } else {
return { return {
type: 'html',
body: cachedData.html, body: cachedData.html,
cacheControl: cacheEntry.cacheControl, cacheControl: cacheEntry.cacheControl,
} }
...@@ -3887,7 +3887,7 @@ export default abstract class Server< ...@@ -3887,7 +3887,7 @@ export default abstract class Server<
`${locale ? `/${locale}` : ''}${pathname}` `${locale ? `/${locale}` : ''}${pathname}`
) )
res.statusCode = 200 res.statusCode = 200
res.setHeader('content-type', 'application/json') res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
res.body('{}') res.body('{}')
res.send() res.send()
return null return null
...@@ -3985,8 +3985,7 @@ export default abstract class Server< ...@@ -3985,8 +3985,7 @@ export default abstract class Server<
// Since favicon.ico is automatically requested by the browser. // Since favicon.ico is automatically requested by the browser.
if (this.renderOpts.dev && ctx.pathname === '/favicon.ico') { if (this.renderOpts.dev && ctx.pathname === '/favicon.ico') {
return { return {
type: 'html', body: RenderResult.EMPTY,
body: RenderResult.fromStatic(''),
} }
} }
const { res, query } = ctx const { res, query } = ctx
...@@ -4079,7 +4078,6 @@ export default abstract class Server< ...@@ -4079,7 +4078,6 @@ export default abstract class Server<
// which is handled in the parent process in development // which is handled in the parent process in development
if (this.renderOpts.dev) { if (this.renderOpts.dev) {
return { return {
type: 'html',
// wait for dev-server to restart before refreshing // wait for dev-server to restart before refreshing
body: RenderResult.fromStatic( body: RenderResult.fromStatic(
` `
...@@ -4095,7 +4093,8 @@ export default abstract class Server< ...@@ -4095,7 +4093,8 @@ export default abstract class Server<
} }
} }
check() check()
</script>` </script>`,
HTML_CONTENT_TYPE_HEADER
), ),
} }
} }
...@@ -4173,8 +4172,7 @@ export default abstract class Server< ...@@ -4173,8 +4172,7 @@ export default abstract class Server<
) )
} }
return { return {
type: 'html', body: RenderResult.fromStatic('Internal Server Error', 'text/plain'),
body: RenderResult.fromStatic('Internal Server Error'),
} }
} }
} }
......
...@@ -84,6 +84,7 @@ import { ...@@ -84,6 +84,7 @@ import {
import { getDefineEnv } from '../../../build/define-env' import { getDefineEnv } from '../../../build/define-env'
import { TurbopackInternalError } from '../../../shared/lib/turbopack/internal-error' import { TurbopackInternalError } from '../../../shared/lib/turbopack/internal-error'
import { normalizePath } from '../../../lib/normalize-path' import { normalizePath } from '../../../lib/normalize-path'
import { JSON_CONTENT_TYPE_HEADER } from '../../../lib/constants'
export type SetupOpts = { export type SetupOpts = {
renderServer: LazyRenderServerInstance renderServer: LazyRenderServerInstance
...@@ -973,7 +974,7 @@ async function startWatcher( ...@@ -973,7 +974,7 @@ async function startWatcher(
if (parsedUrl.pathname?.includes(clientPagesManifestPath)) { if (parsedUrl.pathname?.includes(clientPagesManifestPath)) {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
res.end( res.end(
JSON.stringify({ JSON.stringify({
pages: prevSortedRoutes.filter( pages: prevSortedRoutes.filter(
...@@ -989,7 +990,7 @@ async function startWatcher( ...@@ -989,7 +990,7 @@ async function startWatcher(
parsedUrl.pathname?.includes(devTurbopackMiddlewareManifestPath) parsedUrl.pathname?.includes(devTurbopackMiddlewareManifestPath)
) { ) {
res.statusCode = 200 res.statusCode = 200
res.setHeader('Content-Type', 'application/json; charset=utf-8') res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
res.end(JSON.stringify(serverFields.middleware?.matchers || [])) res.end(JSON.stringify(serverFields.middleware?.matchers || []))
return { finished: true } return { finished: true }
} }
......
...@@ -607,7 +607,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -607,7 +607,6 @@ export default class NextNodeServer extends BaseServer<
res: NodeNextResponse, res: NodeNextResponse,
options: { options: {
result: RenderResult result: RenderResult
type: 'html' | 'json' | 'rsc'
generateEtags: boolean generateEtags: boolean
poweredByHeader: boolean poweredByHeader: boolean
cacheControl: CacheControl | undefined cacheControl: CacheControl | undefined
...@@ -617,7 +616,6 @@ export default class NextNodeServer extends BaseServer< ...@@ -617,7 +616,6 @@ export default class NextNodeServer extends BaseServer<
req: req.originalRequest, req: req.originalRequest,
res: res.originalResponse, res: res.originalResponse,
result: options.result, result: options.result,
type: options.type,
generateEtags: options.generateEtags, generateEtags: options.generateEtags,
poweredByHeader: options.poweredByHeader, poweredByHeader: options.poweredByHeader,
cacheControl: options.cacheControl, cacheControl: options.cacheControl,
......
...@@ -11,8 +11,19 @@ import { ...@@ -11,8 +11,19 @@ import {
} from './stream-utils/node-web-streams-helper' } from './stream-utils/node-web-streams-helper'
import { isAbortError, pipeToNodeResponse } from './pipe-readable' import { isAbortError, pipeToNodeResponse } from './pipe-readable'
import type { RenderResumeDataCache } from './resume-data-cache/resume-data-cache' import type { RenderResumeDataCache } from './resume-data-cache/resume-data-cache'
import { InvariantError } from '../shared/lib/invariant-error'
type ContentTypeOption = string | undefined import type {
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
TEXT_PLAIN_CONTENT_TYPE_HEADER,
} from '../lib/constants'
import type { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-headers'
type ContentTypeOption =
| typeof RSC_CONTENT_TYPE_HEADER // For App Page RSC responses
| typeof HTML_CONTENT_TYPE_HEADER // For App Page, Pages HTML responses
| typeof JSON_CONTENT_TYPE_HEADER // For API routes, Next.js data requests
| typeof TEXT_PLAIN_CONTENT_TYPE_HEADER // For simplified errors
export type AppPageRenderResultMetadata = { export type AppPageRenderResultMetadata = {
flightData?: Buffer flightData?: Buffer
...@@ -70,7 +81,7 @@ export type RenderResultResponse = ...@@ -70,7 +81,7 @@ export type RenderResultResponse =
export type RenderResultOptions< export type RenderResultOptions<
Metadata extends RenderResultMetadata = RenderResultMetadata, Metadata extends RenderResultMetadata = RenderResultMetadata,
> = { > = {
contentType?: ContentTypeOption contentType: ContentTypeOption | null
waitUntil?: Promise<unknown> waitUntil?: Promise<unknown>
metadata: Metadata metadata: Metadata
} }
...@@ -82,7 +93,7 @@ export default class RenderResult< ...@@ -82,7 +93,7 @@ export default class RenderResult<
* The detected content type for the response. This is used to set the * The detected content type for the response. This is used to set the
* `Content-Type` header. * `Content-Type` header.
*/ */
public readonly contentType: ContentTypeOption public readonly contentType: ContentTypeOption | null
/** /**
* The metadata for the response. This is used to set the revalidation times * The metadata for the response. This is used to set the revalidation times
...@@ -98,14 +109,30 @@ export default class RenderResult< ...@@ -98,14 +109,30 @@ export default class RenderResult<
*/ */
private response: RenderResultResponse private response: RenderResultResponse
/**
* A render result that represents an empty response. This is used to
* represent a response that was not found or was already sent.
*/
public static readonly EMPTY = new RenderResult<StaticRenderResultMetadata>(
null,
{ metadata: {}, contentType: null }
)
/** /**
* Creates a new RenderResult instance from a static response. * Creates a new RenderResult instance from a static response.
* *
* @param value the static response value * @param value the static response value
* @param contentType the content type of the response
* @returns a new RenderResult instance * @returns a new RenderResult instance
*/ */
public static fromStatic(value: string | Buffer) { public static fromStatic(
return new RenderResult<StaticRenderResultMetadata>(value, { metadata: {} }) value: string | Buffer,
contentType: ContentTypeOption
) {
return new RenderResult<StaticRenderResultMetadata>(value, {
metadata: {},
contentType,
})
} }
private readonly waitUntil?: Promise<unknown> private readonly waitUntil?: Promise<unknown>
...@@ -144,13 +171,13 @@ export default class RenderResult< ...@@ -144,13 +171,13 @@ export default class RenderResult<
public toUnchunkedBuffer(stream: true): Promise<Buffer> public toUnchunkedBuffer(stream: true): Promise<Buffer>
public toUnchunkedBuffer(stream = false): Promise<Buffer> | Buffer { public toUnchunkedBuffer(stream = false): Promise<Buffer> | Buffer {
if (this.response === null) { if (this.response === null) {
throw new Error('Invariant: null responses cannot be unchunked') throw new InvariantError('null responses cannot be unchunked')
} }
if (typeof this.response !== 'string') { if (typeof this.response !== 'string') {
if (!stream) { if (!stream) {
throw new Error( throw new InvariantError(
'Invariant: dynamic responses cannot be unchunked. This is a bug in Next.js' 'dynamic responses cannot be unchunked. This is a bug in Next.js'
) )
} }
...@@ -171,13 +198,13 @@ export default class RenderResult< ...@@ -171,13 +198,13 @@ export default class RenderResult<
public toUnchunkedString(stream: true): Promise<string> public toUnchunkedString(stream: true): Promise<string>
public toUnchunkedString(stream = false): Promise<string> | string { public toUnchunkedString(stream = false): Promise<string> | string {
if (this.response === null) { if (this.response === null) {
throw new Error('Invariant: null responses cannot be unchunked') throw new InvariantError('null responses cannot be unchunked')
} }
if (typeof this.response !== 'string') { if (typeof this.response !== 'string') {
if (!stream) { if (!stream) {
throw new Error( throw new InvariantError(
'Invariant: dynamic responses cannot be unchunked. This is a bug in Next.js' 'dynamic responses cannot be unchunked. This is a bug in Next.js'
) )
} }
...@@ -188,15 +215,21 @@ export default class RenderResult< ...@@ -188,15 +215,21 @@ export default class RenderResult<
} }
/** /**
* Returns the response if it is a stream, or throws an error if it is a * Returns a readable stream of the response.
* string.
*/ */
private get readable(): ReadableStream<Uint8Array> { private get readable(): ReadableStream<Uint8Array> {
if (this.response === null) { if (this.response === null) {
throw new Error('Invariant: null responses cannot be streamed') // If the response is null, return an empty stream. This behavior is
// intentional as we're now providing the `RenderResult.EMPTY` value.
return new ReadableStream<Uint8Array>({
start(controller) {
controller.close()
},
})
} }
if (typeof this.response === 'string') { if (typeof this.response === 'string') {
throw new Error('Invariant: static responses cannot be streamed') return streamFromString(this.response)
} }
if (Buffer.isBuffer(this.response)) { if (Buffer.isBuffer(this.response)) {
......
...@@ -51,6 +51,8 @@ import { ...@@ -51,6 +51,8 @@ import {
SERVER_PROPS_SSG_CONFLICT, SERVER_PROPS_SSG_CONFLICT,
SSG_GET_INITIAL_PROPS_CONFLICT, SSG_GET_INITIAL_PROPS_CONFLICT,
UNSTABLE_REVALIDATE_RENAME_ERROR, UNSTABLE_REVALIDATE_RENAME_ERROR,
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
} from '../lib/constants' } from '../lib/constants'
import { import {
NEXT_BUILTIN_DOCUMENT, NEXT_BUILTIN_DOCUMENT,
...@@ -1063,7 +1065,10 @@ export async function renderToHTMLImpl( ...@@ -1063,7 +1065,10 @@ export async function renderToHTMLImpl(
// this must come after revalidate is added to renderResultMeta // this must come after revalidate is added to renderResultMeta
if (metadata.isNotFound) { if (metadata.isNotFound) {
return new RenderResult(null, { metadata }) return new RenderResult(null, {
metadata,
contentType: null,
})
} }
} }
...@@ -1179,7 +1184,10 @@ export async function renderToHTMLImpl( ...@@ -1179,7 +1184,10 @@ export async function renderToHTMLImpl(
} }
metadata.isNotFound = true metadata.isNotFound = true
return new RenderResult(null, { metadata }) return new RenderResult(null, {
metadata,
contentType: null,
})
} }
if ('redirect' in data && typeof data.redirect === 'object') { if ('redirect' in data && typeof data.redirect === 'object') {
...@@ -1229,6 +1237,7 @@ export async function renderToHTMLImpl( ...@@ -1229,6 +1237,7 @@ export async function renderToHTMLImpl(
if ((isNextDataRequest && !isSSG) || metadata.isRedirect) { if ((isNextDataRequest && !isSSG) || metadata.isRedirect) {
return new RenderResult(JSON.stringify(props), { return new RenderResult(JSON.stringify(props), {
metadata, metadata,
contentType: JSON_CONTENT_TYPE_HEADER,
}) })
} }
...@@ -1239,7 +1248,7 @@ export async function renderToHTMLImpl( ...@@ -1239,7 +1248,7 @@ export async function renderToHTMLImpl(
} }
// the response might be finished on the getInitialProps call // the response might be finished on the getInitialProps call
if (isResSent(res) && !isSSG) return new RenderResult(null, { metadata }) if (isResSent(res) && !isSSG) return RenderResult.EMPTY
// we preload the buildManifest for auto-export dynamic pages // we preload the buildManifest for auto-export dynamic pages
// to speed up hydrating query values // to speed up hydrating query values
...@@ -1453,7 +1462,10 @@ export async function renderToHTMLImpl( ...@@ -1453,7 +1462,10 @@ export async function renderToHTMLImpl(
async () => renderDocument() async () => renderDocument()
) )
if (!documentResult) { if (!documentResult) {
return new RenderResult(null, { metadata }) return new RenderResult(null, {
metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
})
} }
const dynamicImportsIds = new Set<string | number>() const dynamicImportsIds = new Set<string | number>()
...@@ -1608,7 +1620,10 @@ export async function renderToHTMLImpl( ...@@ -1608,7 +1620,10 @@ export async function renderToHTMLImpl(
hybridAmp, hybridAmp,
}) })
return new RenderResult(optimizedHtml, { metadata }) return new RenderResult(optimizedHtml, {
metadata,
contentType: HTML_CONTENT_TYPE_HEADER,
})
} }
export type PagesRender = ( export type PagesRender = (
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
import RenderResult from '../render-result' import RenderResult from '../render-result'
import { RouteKind } from '../route-kind' import { RouteKind } from '../route-kind'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
export async function fromResponseCacheEntry( export async function fromResponseCacheEntry(
cacheEntry: ResponseCacheEntry cacheEntry: ResponseCacheEntry
...@@ -51,7 +52,10 @@ export async function toResponseCacheEntry( ...@@ -51,7 +52,10 @@ export async function toResponseCacheEntry(
response.value?.kind === CachedRouteKind.PAGES response.value?.kind === CachedRouteKind.PAGES
? ({ ? ({
kind: CachedRouteKind.PAGES, kind: CachedRouteKind.PAGES,
html: RenderResult.fromStatic(response.value.html), html: RenderResult.fromStatic(
response.value.html,
HTML_CONTENT_TYPE_HEADER
),
pageData: response.value.pageData, pageData: response.value.pageData,
headers: response.value.headers, headers: response.value.headers,
status: response.value.status, status: response.value.status,
...@@ -59,7 +63,10 @@ export async function toResponseCacheEntry( ...@@ -59,7 +63,10 @@ export async function toResponseCacheEntry(
: response.value?.kind === CachedRouteKind.APP_PAGE : response.value?.kind === CachedRouteKind.APP_PAGE
? ({ ? ({
kind: CachedRouteKind.APP_PAGE, kind: CachedRouteKind.APP_PAGE,
html: RenderResult.fromStatic(response.value.html), html: RenderResult.fromStatic(
response.value.html,
HTML_CONTENT_TYPE_HEADER
),
rscData: response.value.rscData, rscData: response.value.rscData,
headers: response.value.headers, headers: response.value.headers,
status: response.value.status, status: response.value.status,
......
...@@ -6,7 +6,7 @@ import { isResSent } from '../shared/lib/utils' ...@@ -6,7 +6,7 @@ import { isResSent } from '../shared/lib/utils'
import { generateETag } from './lib/etag' import { generateETag } from './lib/etag'
import fresh from 'next/dist/compiled/fresh' import fresh from 'next/dist/compiled/fresh'
import { getCacheControlHeader } from './lib/cache-control' import { getCacheControlHeader } from './lib/cache-control'
import { RSC_CONTENT_TYPE_HEADER } from '../client/components/app-router-headers' import { HTML_CONTENT_TYPE_HEADER } from '../lib/constants'
export function sendEtagResponse( export function sendEtagResponse(
req: IncomingMessage, req: IncomingMessage,
...@@ -36,7 +36,6 @@ export async function sendRenderResult({ ...@@ -36,7 +36,6 @@ export async function sendRenderResult({
req, req,
res, res,
result, result,
type,
generateEtags, generateEtags,
poweredByHeader, poweredByHeader,
cacheControl, cacheControl,
...@@ -44,7 +43,6 @@ export async function sendRenderResult({ ...@@ -44,7 +43,6 @@ export async function sendRenderResult({
req: IncomingMessage req: IncomingMessage
res: ServerResponse res: ServerResponse
result: RenderResult result: RenderResult
type: 'html' | 'json' | 'rsc'
generateEtags: boolean generateEtags: boolean
poweredByHeader: boolean poweredByHeader: boolean
cacheControl: CacheControl | undefined cacheControl: CacheControl | undefined
...@@ -53,7 +51,7 @@ export async function sendRenderResult({ ...@@ -53,7 +51,7 @@ export async function sendRenderResult({
return return
} }
if (poweredByHeader && type === 'html') { if (poweredByHeader && result.contentType === HTML_CONTENT_TYPE_HEADER) {
res.setHeader('X-Powered-By', 'Next.js') res.setHeader('X-Powered-By', 'Next.js')
} }
...@@ -72,17 +70,8 @@ export async function sendRenderResult({ ...@@ -72,17 +70,8 @@ export async function sendRenderResult({
} }
} }
if (!res.getHeader('Content-Type')) { if (!res.getHeader('Content-Type') && result.contentType) {
res.setHeader( res.setHeader('Content-Type', result.contentType)
'Content-Type',
result.contentType
? result.contentType
: type === 'rsc'
? RSC_CONTENT_TYPE_HEADER
: type === 'json'
? 'application/json'
: 'text/html; charset=utf-8'
)
} }
if (payload) { if (payload) {
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
} from './uint8array-helpers' } from './uint8array-helpers'
import { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants' import { MISSING_ROOT_TAGS_ERROR } from '../../shared/lib/errors/constants'
import { insertBuildIdComment } from '../../shared/lib/segment-cache/output-export-prefetch-encoding' import { insertBuildIdComment } from '../../shared/lib/segment-cache/output-export-prefetch-encoding'
import { InvariantError } from '../../shared/lib/invariant-error'
function voidCatch() { function voidCatch() {
// this catcher is designed to be used with pipeTo where we expect the underlying // this catcher is designed to be used with pipeTo where we expect the underlying
...@@ -32,7 +33,7 @@ export function chainStreams<T>( ...@@ -32,7 +33,7 @@ export function chainStreams<T>(
// We could encode this invariant in the arguments but current uses of this function pass // We could encode this invariant in the arguments but current uses of this function pass
// use spread so it would be missed by // use spread so it would be missed by
if (streams.length === 0) { if (streams.length === 0) {
throw new Error('Invariant: chainStreams requires at least one stream') throw new InvariantError('chainStreams requires at least one stream')
} }
// If we only have 1 stream we fast path it by returning just this stream // If we only have 1 stream we fast path it by returning just this stream
......
...@@ -35,6 +35,7 @@ import { getEdgeInstrumentationModule } from './web/globals' ...@@ -35,6 +35,7 @@ import { getEdgeInstrumentationModule } from './web/globals'
import type { ServerOnInstrumentationRequestError } from './app-render/types' import type { ServerOnInstrumentationRequestError } from './app-render/types'
import { getEdgePreviewProps } from './web/get-edge-preview-props' import { getEdgePreviewProps } from './web/get-edge-preview-props'
import { NoFallbackError } from '../shared/lib/no-fallback-error.external' import { NoFallbackError } from '../shared/lib/no-fallback-error.external'
import { HTML_CONTENT_TYPE_HEADER } from '../lib/constants'
interface WebServerOptions extends Options { interface WebServerOptions extends Options {
buildId: string buildId: string
...@@ -258,7 +259,6 @@ export default class NextWebServer extends BaseServer< ...@@ -258,7 +259,6 @@ export default class NextWebServer extends BaseServer<
res: WebNextResponse, res: WebNextResponse,
options: { options: {
result: RenderResult result: RenderResult
type: 'html' | 'json'
generateEtags: boolean generateEtags: boolean
poweredByHeader: boolean poweredByHeader: boolean
cacheControl: CacheControl | undefined cacheControl: CacheControl | undefined
...@@ -268,19 +268,15 @@ export default class NextWebServer extends BaseServer< ...@@ -268,19 +268,15 @@ export default class NextWebServer extends BaseServer<
// Add necessary headers. // Add necessary headers.
// @TODO: Share the isomorphic logic with server/send-payload.ts. // @TODO: Share the isomorphic logic with server/send-payload.ts.
if (options.poweredByHeader && options.type === 'html') { if (
options.poweredByHeader &&
options.result.contentType === HTML_CONTENT_TYPE_HEADER
) {
res.setHeader('X-Powered-By', 'Next.js') res.setHeader('X-Powered-By', 'Next.js')
} }
if (!res.getHeader('Content-Type')) { if (!res.getHeader('Content-Type') && options.result.contentType) {
res.setHeader( res.setHeader('Content-Type', options.result.contentType)
'Content-Type',
options.result.contentType
? options.result.contentType
: options.type === 'json'
? 'application/json'
: 'text/html; charset=utf-8'
)
} }
let promise: Promise<void> | undefined let promise: Promise<void> | undefined
......
...@@ -155,12 +155,16 @@ describe('unrecognized server actions', () => { ...@@ -155,12 +155,16 @@ describe('unrecognized server actions', () => {
// We also don't seem to display the error page correctly, // We also don't seem to display the error page correctly,
// and the response is inconsistent between nodejs and edge. // and the response is inconsistent between nodejs and edge.
expect(response.status()).toBe(runtime === 'nodejs' ? 405 : 500) expect(response.status()).toBe(runtime === 'nodejs' ? 405 : 500)
expect(response.headers()['content-type']).toStartWith('text/html') expect(response.headers()['content-type']).toStartWith(
runtime === 'nodejs' ? 'text/html' : 'text/plain'
)
} else { } else {
// FIXME: Currently, an unrecognized id in an MPA action results in a 500. // FIXME: Currently, an unrecognized id in an MPA action results in a 500.
// This is not ideal, and ignores all nested `error.js` files, only showing the topmost one. // This is not ideal, and ignores all nested `error.js` files, only showing the topmost one.
expect(response.status()).toBe(500) expect(response.status()).toBe(500)
expect(response.headers()['content-type']).toStartWith('text/html') expect(response.headers()['content-type']).toStartWith(
runtime === 'nodejs' ? 'text/html' : 'text/plain'
)
// In dev, the 500 page doesn't have any SSR'd html, so it won't show anything without JS. // In dev, the 500 page doesn't have any SSR'd html, so it won't show anything without JS.
if (!isNextDev) { if (!isNextDev) {
expect(await browser.elementByCss('body').text()).toContain( expect(await browser.elementByCss('body').text()).toContain(
......
...@@ -54,7 +54,9 @@ describe('i18n-data-route', () => { ...@@ -54,7 +54,9 @@ describe('i18n-data-route', () => {
const res = await next.fetch(url) const res = await next.fetch(url)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('application/json') expect(res.headers.get('content-type')).toStartWith(
'application/json'
)
const data = await res.json() const data = await res.json()
checkDataRoute(data, page) checkDataRoute(data, page)
} }
...@@ -80,7 +82,7 @@ describe('i18n-data-route', () => { ...@@ -80,7 +82,7 @@ describe('i18n-data-route', () => {
} }
const res = await next.fetch(url) const res = await next.fetch(url)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('application/json') expect(res.headers.get('content-type')).toStartWith('application/json')
const data = await res.json() const data = await res.json()
checkDataRoute(data, page) checkDataRoute(data, page)
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment