Commit 88deb12b authored by Jiachi Liu's avatar Jiachi Liu

[metadata] re-insert icons to head for streamed metadata (#76915)

### What

Re-insert the metadata icons under body tag into head tag to ensure they
can be proper displayed.

### Why

* For chromium based browsers (Chrome, Edge, etc.) and Safari, icons
need to stay under `<head>` to be picked up by the browser. Firefox
doesn't have this requirement.
* Firefox will always render svg > icon > png, so it doesn't matter to
it.


Made a test in https://icons-order-test.vercel.app/, you can play with
the test cases here. These links can see the comparsion of the approach
in the this PR.

During deployment it's very hard to verify Safari as it's pretty broken.
But deploymet works well.
After we re-insert the icon from body into head, they can be properly
displayed across all the browsers.

Note: We insert the script during streaming rather than using a jsx
element right after metadata to avoid the hydration errors

Closes #76810
Closes NDX-951
parent f4552826
import type { ResolvedMetadata } from '../types/metadata-interface'
import type { Icon, IconDescriptor } from '../types/metadata-types'
import React from 'react'
import { MetaFilter } from './meta'
function IconDescriptorLink({ icon }: { icon: IconDescriptor }) {
......
......@@ -317,7 +317,7 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
}
function createDivergedMetadataComponents(
Metadata: React.ComponentType<{}>,
Metadata: React.ComponentType,
serveStreamingMetadata: boolean
): {
StaticMetadata: React.ComponentType<{}>
......@@ -326,8 +326,9 @@ function createDivergedMetadataComponents(
function EmptyMetadata() {
return null
}
const StreamingMetadata: React.ComponentType<{}> | null =
serveStreamingMetadata ? Metadata : null
const StreamingMetadata: React.ComponentType | null = serveStreamingMetadata
? Metadata
: null
const StaticMetadata: React.ComponentType<{}> = serveStreamingMetadata
? EmptyMetadata
......@@ -1711,7 +1712,7 @@ async function renderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } =
createServerInsertedMetadata()
createServerInsertedMetadata(ctx.nonce)
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
......@@ -2299,9 +2300,9 @@ async function spawnDynamicValidationInDev(
}
}
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const { ServerInsertedMetadataProvider } = createServerInsertedMetadata()
const nonce = '1'
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const { ServerInsertedMetadataProvider } = createServerInsertedMetadata(nonce)
if (initialServerStream) {
const [warmupStream, renderStream] = initialServerStream.tee()
......@@ -2584,7 +2585,7 @@ async function prerenderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } =
createServerInsertedMetadata()
createServerInsertedMetadata(ctx.nonce)
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
......
......@@ -40,7 +40,7 @@ export function createComponentTree(props: {
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
StreamingMetadata: React.ComponentType<{}> | null
StreamingMetadata: React.ComponentType | null
StreamingMetadataOutlet: React.ComponentType
}): Promise<CacheNodeSeedData> {
return getTracer().trace(
......@@ -92,7 +92,7 @@ async function createComponentTreeInternal({
missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks
authInterrupts: boolean
StreamingMetadata: React.ComponentType<{}> | null
StreamingMetadata: React.ComponentType | null
StreamingMetadataOutlet: React.ComponentType | null
}): Promise<CacheNodeSeedData> {
const {
......
......@@ -6,7 +6,15 @@ import {
} from '../../../shared/lib/server-inserted-metadata.shared-runtime'
import { renderToString } from '../render-to-string'
export function createServerInsertedMetadata() {
/**
* For chromium based browsers (Chrome, Edge, etc.) and Safari,
* icons need to stay under <head> to be picked up by the browser.
*
*/
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 => {
......@@ -34,7 +42,12 @@ export function createServerInsertedMetadata() {
metadataToFlush = metadataResolver()
const html = await renderToString({
renderToReadableStream,
element: <>{metadataToFlush}</>,
element: (
<>
{metadataToFlush}
<script nonce={nonce}>{REINSERT_ICON_SCRIPT}</script>
</>
),
})
return html
......
import { Metadata } from 'next'
import Link from 'next/link'
import { connection } from 'next/server'
export default function Page() {
return (
<>
<Link id="custom-icon-sub-link" href="/custom-icon/sub">
Go to another page with custom icon
</Link>
</>
)
}
export async function generateMetadata(): Promise<Metadata> {
await connection()
await new Promise((resolve) => setTimeout(resolve, 300))
return {
icons: {
// add version query to avoid caching on client side with multiple navs
icon: `/heart.png?v=${Math.round(Math.random() * 1000)}`,
},
}
}
import { type Metadata } from 'next'
import Link from 'next/link'
import { connection } from 'next/server'
export async function generateMetadata(): Promise<Metadata> {
await connection()
await new Promise((resolve) => setTimeout(resolve, 300))
return {
icons: {
// add version query to avoid caching on client side with multiple navs
icon: `/star.png?v=${Math.round(Math.random() * 1000)}`,
},
}
}
export default function Page() {
return (
<>
<Link id="custom-icon-link" href="/custom-icon">
Back to previous page with custom icon
</Link>
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('app-dir - metadata-icons', () => {
const { next } = nextTestSetup({
......@@ -28,4 +29,66 @@ describe('app-dir - metadata-icons', () => {
'/shortcut-icon-nested.png'
)
})
it('should re-insert the body icons into the head', async () => {
const browser = await next.browser('/custom-icon')
await retry(async () => {
const iconsInBody = await browser.elementsByCss('body link[rel="icon"]')
const iconsInHead = await browser.elementsByCss('head link[rel="icon"]')
// moved to head
expect(iconsInBody.length).toBe(0)
// re-inserted favicon.ico + /heart.png
expect(iconsInHead.length).toBe(2)
})
})
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()
await retry(async () => {
const url = await browser.url()
expect(url).toMatch(/\/custom-icon\/sub$/)
})
await retry(async () => {
const iconsInHead = await browser.elementsByCss('head link[rel="icon"]')
let iconUrls = await Promise.all(
iconsInHead.map(
async (el) => (await el.getAttribute('href')).split('?')[0]
)
)
// Pick last 2 icons
// In non-headless mode, the icons are deduped;
// In headless mode, the icons are not deduped
expect(iconUrls.length === 4 ? iconUrls.slice(2) : iconUrls).toEqual([
'/favicon.ico',
'/star.png',
])
})
// navigate back
await browser.elementByCss('#custom-icon-link').click()
await retry(async () => {
const url = await browser.url()
expect(url).toMatch(/\/custom-icon$/)
})
await retry(async () => {
const icons = await browser.elementsByCss('head link[rel="icon"]')
const iconUrls = await Promise.all(
icons.map(async (el) => (await el.getAttribute('href')).split('?')[0])
)
// Pick last 2 icons
// In non-headless mode, the icons are deduped;
// In headless mode, the icons are not deduped
expect(iconUrls.length === 4 ? iconUrls.slice(2) : iconUrls).toEqual([
'/favicon.ico',
'/heart.png',
])
})
})
})
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