Unverified Commit 5325afa6 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[metadata] refactor to remove async metadata (#78495)

parent 286eefe6
......@@ -3,15 +3,6 @@
import { Suspense, use } from 'react'
import type { StreamingMetadataResolvedState } from './types'
export const AsyncMetadata =
typeof window === 'undefined'
? (
require('./server-inserted-metadata') as typeof import('./server-inserted-metadata')
).ServerInsertMetadata
: (
require('./browser-resolved-metadata') as typeof import('./browser-resolved-metadata')
).BrowserResolvedMetadata
function MetadataOutlet({
promise,
}: {
......
import { use } from 'react'
import type { StreamingMetadataResolvedState } from './types'
export function BrowserResolvedMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
const { metadata, error } = use(promise)
// If there's metadata error on client, discard the browser metadata
// and let metadata outlet deal with the error. This will avoid the duplication metadata.
if (error) return null
return metadata
}
import { use, useContext } from 'react'
import {
type MetadataResolver,
ServerInsertedMetadataContext,
} from '../../../shared/lib/server-inserted-metadata.shared-runtime'
import type { StreamingMetadataResolvedState } from './types'
// Receives a metadata resolver setter from the context, and will pass the metadata resolving promise to
// the context where we gonna use it to resolve the metadata, and render as string to append in <body>.
const useServerInsertedMetadata = (metadataResolver: MetadataResolver) => {
const setMetadataResolver = useContext(ServerInsertedMetadataContext)
if (setMetadataResolver) {
setMetadataResolver(metadataResolver)
}
}
export function ServerInsertMetadata({
promise,
}: {
promise: Promise<StreamingMetadataResolvedState>
}) {
// Apply use() to the metadata promise to suspend the rendering in SSR.
const { metadata } = use(promise)
// Insert metadata into the HTML stream through the `useServerInsertedMetadata`
useServerInsertedMetadata(() => metadata)
return null
}
'use client'
// This is a client component that only renders during SSR,
// but will be replaced during streaming with an icon insertion script tag.
// We don't want it to be presented anywhere so it's only visible during streaming,
// right after the icon meta tags so that browser can pick it up as soon as it's rendered.
// Note: we don't just emit the script here because we only need the script if it's not in the head,
// and we need it to be hoistable alongside the other metadata but sync scripts are not hoistable.
export const IconMark = () => {
if (typeof window !== 'undefined') {
return null
}
return <meta name="«nxt-icon»" />
}
import type { ResolvedMetadata } from '../types/metadata-interface'
import type { Icon, IconDescriptor } from '../types/metadata-types'
import { IconMark } from './icon-mark'
import { MetaFilter } from './meta'
......@@ -27,6 +28,14 @@ export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) {
const appleList = icons.apple
const otherList = icons.other
const hasIcon = Boolean(
shortcutList?.length ||
iconList?.length ||
appleList?.length ||
otherList?.length
)
if (!hasIcon) return null
return MetaFilter([
shortcutList
? shortcutList.map((icon) => IconLink({ rel: 'shortcut icon', icon }))
......@@ -36,5 +45,6 @@ export function IconsMetadata({ icons }: { icons: ResolvedMetadata['icons'] }) {
? appleList.map((icon) => IconLink({ rel: 'apple-touch-icon', icon }))
: null,
otherList ? otherList.map((icon) => IconDescriptorLink({ icon })) : null,
hasIcon ? <IconMark /> : null,
])
}
......@@ -38,10 +38,7 @@ import {
METADATA_BOUNDARY_NAME,
VIEWPORT_BOUNDARY_NAME,
} from './metadata-constants'
import {
AsyncMetadata,
AsyncMetadataOutlet,
} from '../../client/components/metadata/async-metadata'
import { AsyncMetadataOutlet } from '../../client/components/metadata/async-metadata'
import { isPostpone } from '../../server/lib/router-utils/is-postpone'
import { createServerSearchParamsForMetadata } from '../../server/request/search-params'
import { createServerPathnameForMetadata } from '../../server/request/pathname'
......@@ -211,18 +208,22 @@ export function createMetadataComponents({
}
}
}
async function Metadata() {
const promise = resolveFinalMetadata()
if (serveStreamingMetadata) {
return (
<div hidden>
<Suspense fallback={null}>
<AsyncMetadata promise={promise} />
</Suspense>
</div>
)
function Metadata() {
if (!serveStreamingMetadata) {
return <MetadataResolver />
}
const metadataState = await promise
return (
<div hidden>
<Suspense fallback={null}>
<MetadataResolver />
</Suspense>
</div>
)
}
async function MetadataResolver() {
const metadataState = await resolveFinalMetadata()
return metadataState.metadata
}
......
......@@ -985,7 +985,7 @@ async function getErrorRSCPayload(
const seedData: CacheNodeSeedData = [
initialTree[0],
<html id="__next_error__">
<head>{metadata}</head>
<head></head>
<body>
{process.env.NODE_ENV !== 'production' && err ? (
<template
......@@ -1043,7 +1043,6 @@ function App<T>({
preinitScripts,
clientReferenceManifest,
ServerInsertedHTMLProvider,
ServerInsertedMetadataProvider,
gracefullyDegrade,
nonce,
}: {
......@@ -1051,7 +1050,6 @@ function App<T>({
preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
ServerInsertedMetadataProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string
}): JSX.Element {
......@@ -1091,16 +1089,14 @@ function App<T>({
nonce,
}}
>
<ServerInsertedMetadataProvider>
<ServerInsertedHTMLProvider>
<AppRouter
actionQueue={actionQueue}
globalErrorComponentAndStyles={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
</ServerInsertedMetadataProvider>
<ServerInsertedHTMLProvider>
<AppRouter
actionQueue={actionQueue}
globalErrorComponentAndStyles={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
</HeadManagerContext.Provider>
)
}
......@@ -1112,7 +1108,6 @@ function ErrorApp<T>({
reactServerStream,
preinitScripts,
clientReferenceManifest,
ServerInsertedMetadataProvider,
ServerInsertedHTMLProvider,
gracefullyDegrade,
nonce,
......@@ -1120,7 +1115,6 @@ function ErrorApp<T>({
reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedMetadataProvider: React.ComponentType<{ children: JSX.Element }>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string
......@@ -1152,16 +1146,14 @@ function ErrorApp<T>({
const actionQueue = createMutableActionQueue(initialState, null)
return (
<ServerInsertedMetadataProvider>
<ServerInsertedHTMLProvider>
<AppRouter
actionQueue={actionQueue}
globalErrorComponentAndStyles={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
</ServerInsertedMetadataProvider>
<ServerInsertedHTMLProvider>
<AppRouter
actionQueue={actionQueue}
globalErrorComponentAndStyles={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
)
}
......@@ -1781,8 +1773,7 @@ async function renderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } =
createServerInsertedMetadata(nonce)
const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
......@@ -1979,7 +1970,6 @@ async function renderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
nonce={nonce}
gracefullyDegrade={!!botType}
/>,
......@@ -2018,7 +2008,6 @@ async function renderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -2171,7 +2160,6 @@ async function renderToStream(
element: (
<ErrorApp
reactServerStream={errorServerStream}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest}
......@@ -2276,7 +2264,6 @@ async function spawnDynamicValidationInDev(
// that are provided during the actual prerenderToStream.
const preinitScripts = () => {}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const { ServerInsertedMetadataProvider } = createServerInsertedMetadata(nonce)
const rootParams = getRootParams(
ComponentMod.tree,
......@@ -2443,7 +2430,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -2596,7 +2582,6 @@ async function spawnDynamicValidationInDev(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -2746,8 +2731,7 @@ async function prerenderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } =
createServerInsertedMetadata(nonce)
const getServerInsertedMetadata = createServerInsertedMetadata(nonce)
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
......@@ -3039,7 +3023,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -3200,7 +3183,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -3333,7 +3315,6 @@ async function prerenderToStream(
preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -3432,7 +3413,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -3565,7 +3545,6 @@ async function prerenderToStream(
preinitScripts={() => {}}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -3645,7 +3624,6 @@ async function prerenderToStream(
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!botType}
nonce={nonce}
/>,
......@@ -3807,7 +3785,6 @@ async function prerenderToStream(
element: (
<ErrorApp
reactServerStream={errorServerStream}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest}
......
import React from 'react'
import { renderToReadableStream } from 'react-dom/server.edge'
import {
ServerInsertedMetadataContext,
type MetadataResolver,
} from '../../../shared/lib/server-inserted-metadata.shared-runtime'
import { renderToString } from '../render-to-string'
/**
* For chromium based browsers (Chrome, Edge, etc.) and Safari,
* icons need to stay under <head> to be picked up by the browser.
......@@ -15,42 +7,14 @@ const REINSERT_ICON_SCRIPT = `\
document.querySelectorAll('body link[rel="icon"], body link[rel="apple-touch-icon"]').forEach(el => document.head.appendChild(el))`
export function createServerInsertedMetadata(nonce: string | undefined) {
let metadataResolver: MetadataResolver | null = null
let metadataToFlush: React.ReactNode = null
const setMetadataResolver = (resolver: MetadataResolver): void => {
metadataResolver = resolver
}
return {
ServerInsertedMetadataProvider: ({
children,
}: {
children: React.ReactNode
}) => {
return (
<ServerInsertedMetadataContext.Provider value={setMetadataResolver}>
{children}
</ServerInsertedMetadataContext.Provider>
)
},
async getServerInsertedMetadata(): Promise<string> {
if (!metadataResolver || metadataToFlush) {
return ''
}
let inserted = false
metadataToFlush = metadataResolver()
const html = await renderToString({
renderToReadableStream,
element: (
<>
{metadataToFlush}
<script nonce={nonce}>{REINSERT_ICON_SCRIPT}</script>
</>
),
})
return async function getServerInsertedMetadata(): Promise<string> {
if (inserted) {
return ''
}
return html
},
inserted = true
return `<script nonce="${nonce}">${REINSERT_ICON_SCRIPT}</script>`
}
}
......@@ -155,7 +155,7 @@ import {
getBuiltinRequestContext,
type WaitUntil,
} from './after/builtin-request-context'
import { ENCODED_TAGS } from './stream-utils/encodedTags'
import { ENCODED_TAGS } from './stream-utils/encoded-tags'
import { NextRequestHint } from './web/adapter'
import { getRevalidateReason } from './instrumentation/utils'
import { RouteKind } from './route-kind'
......
export * as HeadManagerContext from '../../../../../shared/lib/head-manager-context.shared-runtime'
export * as ServerInsertedHtml from '../../../../../shared/lib/server-inserted-html.shared-runtime'
export * as ServerInsertedMetadata from '../../../../../shared/lib/server-inserted-metadata.shared-runtime'
export * as AppRouterContext from '../../../../../shared/lib/app-router-context.shared-runtime'
export * as HooksClientContext from '../../../../../shared/lib/hooks-client-context.shared-runtime'
export * as RouterContext from '../../../../../shared/lib/router-context.shared-runtime'
......
......@@ -18,4 +18,13 @@ export const ENCODED_TAGS = {
60, 47, 98, 111, 100, 121, 62, 60, 47, 104, 116, 109, 108, 62,
]),
},
META: {
// Only the match the prefix cause the suffix can be different wether it's xml compatible or not ">" or "/>"
// <meta name="«nxt-icon»"
// This is a special mark that will be replaced by the icon insertion script tag.
ICON_MARK: new Uint8Array([
60, 109, 101, 116, 97, 32, 110, 97, 109, 101, 61, 34, 194, 171, 110, 120,
116, 45, 105, 99, 111, 110, 194, 187, 34,
]),
},
} as const
......@@ -2,7 +2,7 @@ import { getTracer } from '../lib/trace/tracer'
import { AppRenderSpan } from '../lib/trace/constants'
import { DetachedPromise } from '../../lib/detached-promise'
import { scheduleImmediate, atLeastOneTask } from '../../lib/scheduler'
import { ENCODED_TAGS } from './encodedTags'
import { ENCODED_TAGS } from './encoded-tags'
import {
indexOfUint8Array,
isEquivalentUint8Arrays,
......@@ -193,6 +193,89 @@ export function renderToInitialFizzStream({
)
}
function createMetadataTransformStream(
insert: () => Promise<string> | string
): TransformStream<Uint8Array, Uint8Array> {
let chunkIndex = -1
let isMarkRemoved = false
return new TransformStream({
async transform(chunk, controller) {
let iconMarkIndex = -1
let closedHeadIndex = -1
chunkIndex++
if (isMarkRemoved) {
controller.enqueue(chunk)
return
}
let iconMarkLength = 0
// Only search for the closed head tag once
if (iconMarkIndex === -1) {
iconMarkIndex = indexOfUint8Array(chunk, ENCODED_TAGS.META.ICON_MARK)
if (iconMarkIndex === -1) {
controller.enqueue(chunk)
return
} else {
// When we found the `<meta name="«nxt-icon»"` tag prefix, we will remove it from the chunk.
// Its close tag could either be `/>` or `>`, checking the next char to ensure we cover both cases.
iconMarkLength = ENCODED_TAGS.META.ICON_MARK.length
// Check if next char is /, this is for xml mode.
if (chunk[iconMarkIndex + iconMarkLength] === 47) {
iconMarkLength += 2
} else {
// The last char is `>`
iconMarkLength++
}
}
}
// Check if icon mark is inside <head> tag in the first chunk.
if (chunkIndex === 0) {
closedHeadIndex = indexOfUint8Array(chunk, ENCODED_TAGS.CLOSED.HEAD)
// The mark icon is located in the 1st chunk before the head tag.
// We do not need to insert the script tag in this case because it's in the head.
// Just remove the icon mark from the chunk.
if (iconMarkIndex < closedHeadIndex && iconMarkIndex !== -1) {
const replaced = new Uint8Array(chunk.length - iconMarkLength)
// Remove the icon mark from the chunk.
replaced.set(chunk.subarray(0, iconMarkIndex))
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex
)
chunk = replaced
isMarkRemoved = true
}
} else {
// When it's appeared in the following chunks, we'll need to
// remove the mark and then insert the script tag at that position.
const insertion = await insert()
const encodedInsertion = encoder.encode(insertion)
const insertionLength = encodedInsertion.length
// Replace the icon mark with the hoist script or empty string.
const replaced = new Uint8Array(
chunk.length - iconMarkLength + insertionLength
)
// Set the first part of the chunk, before the icon mark.
replaced.set(chunk.subarray(0, iconMarkIndex))
// Set the insertion after the icon mark.
replaced.set(encodedInsertion, iconMarkIndex)
// Set the rest of the chunk after the icon mark.
replaced.set(
chunk.subarray(iconMarkIndex + iconMarkLength),
iconMarkIndex + insertionLength
)
chunk = replaced
isMarkRemoved = true
}
controller.enqueue(chunk)
},
})
}
function createHeadInsertionTransformStream(
insert: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> {
......@@ -564,8 +647,8 @@ export async function continueFizzStream(
// Buffer everything to avoid flushing too frequently
createBufferedTransformStream(),
// Insert generated metadata
createHeadInsertionTransformStream(getServerInsertedMetadata),
// Transform metadata
createMetadataTransformStream(getServerInsertedMetadata),
// Insert suffix content
suffixUnclosed != null && suffixUnclosed.length > 0
......@@ -607,10 +690,8 @@ export async function continueDynamicPrerender(
.pipeThrough(createStripDocumentClosingTagsTransform())
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert generated metadata
.pipeThrough(
createHeadInsertionTransformStream(getServerInsertedMetadata)
)
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
)
}
......@@ -634,10 +715,8 @@ export async function continueStaticPrerender(
.pipeThrough(createBufferedTransformStream())
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert generated metadata to head
.pipeThrough(
createHeadInsertionTransformStream(getServerInsertedMetadata)
)
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(createMergedTransformStream(inlinedDataStream))
// Close tags should always be deferred to the end
......@@ -665,10 +744,8 @@ export async function continueDynamicHTMLResume(
.pipeThrough(createBufferedTransformStream())
// Insert generated tags to head
.pipeThrough(createHeadInsertionTransformStream(getServerInsertedHTML))
// Insert generated metadata to body
.pipeThrough(
createHeadInsertionTransformStream(getServerInsertedMetadata)
)
// Transform metadata
.pipeThrough(createMetadataTransformStream(getServerInsertedMetadata))
// Insert the inlined data (Flight data, form state, etc.) stream into the HTML
.pipeThrough(createMergedTransformStream(inlinedDataStream))
// Close tags should always be deferred to the end
......
'use client'
import type React from 'react'
import { createContext } from 'react'
export type MetadataResolver = () => React.ReactNode
type MetadataResolverSetter = (m: MetadataResolver) => void
export const ServerInsertedMetadataContext =
createContext<MetadataResolverSetter | null>(null)
......@@ -491,6 +491,12 @@ describe('app dir - css', () => {
const matches = initialHtml
.match(/\/_next\/static\/css\/.+?\.css/g)
// The same css chunk could be split into 2 RSC script
// normalize "/_next/static/css/app/\"])</script><script>self.__next_f.push([1,\"not-found.css"
// to "/_next/static/css/app/not-found.css"
.map((href) =>
href.replace('"])</script><script>self.__next_f.push([1,"', '')
)
.sort()
// Heavy on testing React implementation details.
......
......@@ -44,6 +44,27 @@ describe('app-dir - metadata-icons', () => {
})
})
it('should not contain icon insertion script when metadata is rendered in head', async () => {
const iconInsertionScript = `document.querySelectorAll('body link[rel="icon"], body link[rel="apple-touch-icon"]').forEach(el => document.head.appendChild(el))`
const suspendedHtml = await next.render('/custom-icon')
expect(suspendedHtml).toContain(iconInsertionScript)
})
it('should not contain icon replacement mark in html or after hydration', async () => {
const html = await next.render('/custom-icon')
expect(html).not.toContain('<meta name="«nxt-icon»" content=""/>')
expect(html).not.toContain('«nxt-icon»')
const browser = await next.browser('/custom-icon')
const metaTags = await browser.elementsByCss('meta')
// none of them has [name="«nxt-icon»"]
const names = await Promise.all(
metaTags.map((el) => el.getAttribute('name'))
)
expect(names).not.toContain('«nxt-icon»')
})
it('should re-insert the apple icons into the head after navigation', async () => {
const browser = await next.browser('/custom-icon')
await browser.elementByCss('#custom-icon-sub-link').click()
......
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
......@@ -15,7 +15,9 @@ describe('app-dir - metadata-streaming', () => {
const $ = await next.render$('/parallel-routes')
expect($('title').length).toBe(1)
expect($('head title').text()).toBe('parallel title')
// We can't ensure if it's inserted into head or body since it's a race condition,
// where sometimes the metadata can be suspended.
expect($('title').text()).toBe('parallel title')
// validate behavior remains the same on client navigations
await browser.elementByCss('[href="/parallel-routes/test-page"]').click()
......
......@@ -157,8 +157,10 @@ describe('app-dir - metadata-streaming', () => {
describe('static', () => {
it('should render static metadata in the head', async () => {
const $ = await next.render$('/static/full')
// We can't ensure if it's inserted into head or body since it's a race condition,
// where sometimes the metadata can be suspended.
expect($('title').length).toBe(1)
expect($('head title').text()).toBe('static page')
expect($('title').text()).toBe('static page')
})
it('should determine dynamic metadata in build and render in the body', async () => {
......
......@@ -10,13 +10,18 @@ describe('app dir - metadata dynamic routes suspense', () => {
return
}
it('should render metadata in head even root layout is wrapped with Suspense', async () => {
const $ = await next.render$('/')
it('should render metadata in head when root layout is wrapped with Suspense for bot requests', async () => {
const $ = await next.render$('/', undefined, {
headers: {
'User-Agent': 'Discordbot/2.0;',
},
})
expect($('head title').text()).toBe('My title')
expect($('head meta[name="application-name"]').attr('content')).toBe(
'suspense-app'
)
expect($('body meta').length).toBe(0)
// unique title
expect($('title').length).toBe(1)
})
})
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
......@@ -17,9 +17,8 @@
{
"name": "next"
}
],
"target": "ES2017"
]
},
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
"exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
}
export default function Page() {
return <h1>I'm still a valid page</h1>
return <h1>I am still a valid page</h1>
}
......@@ -22,7 +22,7 @@ describe('app dir - not-found - conflict route', () => {
it('should allow to have a valid /not-found route', async () => {
const html = await next.render('/not-found')
expect(html).toContain("I'm still a valid page")
expect(html).toContain('I am still a valid page')
})
}
......
......@@ -169,7 +169,7 @@ describe('opentelemetry', () => {
},
{
attributes: {
'next.clientComponentLoadCount': 8,
'next.clientComponentLoadCount': 7,
'next.span_type':
'NextNodeServer.clientComponentLoading',
},
......
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