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 { ResolvedMetadata } from '../types/metadata-interface'
import type { Icon, IconDescriptor } from '../types/metadata-types' import type { Icon, IconDescriptor } from '../types/metadata-types'
import React from 'react'
import { MetaFilter } from './meta' import { MetaFilter } from './meta'
function IconDescriptorLink({ icon }: { icon: IconDescriptor }) { function IconDescriptorLink({ icon }: { icon: IconDescriptor }) {
......
...@@ -317,7 +317,7 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree { ...@@ -317,7 +317,7 @@ function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
} }
function createDivergedMetadataComponents( function createDivergedMetadataComponents(
Metadata: React.ComponentType<{}>, Metadata: React.ComponentType,
serveStreamingMetadata: boolean serveStreamingMetadata: boolean
): { ): {
StaticMetadata: React.ComponentType<{}> StaticMetadata: React.ComponentType<{}>
...@@ -326,8 +326,9 @@ function createDivergedMetadataComponents( ...@@ -326,8 +326,9 @@ function createDivergedMetadataComponents(
function EmptyMetadata() { function EmptyMetadata() {
return null return null
} }
const StreamingMetadata: React.ComponentType<{}> | null = const StreamingMetadata: React.ComponentType | null = serveStreamingMetadata
serveStreamingMetadata ? Metadata : null ? Metadata
: null
const StaticMetadata: React.ComponentType<{}> = serveStreamingMetadata const StaticMetadata: React.ComponentType<{}> = serveStreamingMetadata
? EmptyMetadata ? EmptyMetadata
...@@ -1711,7 +1712,7 @@ async function renderToStream( ...@@ -1711,7 +1712,7 @@ async function renderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML() createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } = const { ServerInsertedMetadataProvider, getServerInsertedMetadata } =
createServerInsertedMetadata() createServerInsertedMetadata(ctx.nonce)
const tracingMetadata = getTracedMetadata( const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(), getTracer().getTracePropagationData(),
...@@ -2299,9 +2300,9 @@ async function spawnDynamicValidationInDev( ...@@ -2299,9 +2300,9 @@ async function spawnDynamicValidationInDev(
} }
} }
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const { ServerInsertedMetadataProvider } = createServerInsertedMetadata()
const nonce = '1' const nonce = '1'
const { ServerInsertedHTMLProvider } = createServerInsertedHTML()
const { ServerInsertedMetadataProvider } = createServerInsertedMetadata(nonce)
if (initialServerStream) { if (initialServerStream) {
const [warmupStream, renderStream] = initialServerStream.tee() const [warmupStream, renderStream] = initialServerStream.tee()
...@@ -2584,7 +2585,7 @@ async function prerenderToStream( ...@@ -2584,7 +2585,7 @@ async function prerenderToStream(
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } = const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML() createServerInsertedHTML()
const { ServerInsertedMetadataProvider, getServerInsertedMetadata } = const { ServerInsertedMetadataProvider, getServerInsertedMetadata } =
createServerInsertedMetadata() createServerInsertedMetadata(ctx.nonce)
const tracingMetadata = getTracedMetadata( const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(), getTracer().getTracePropagationData(),
......
...@@ -40,7 +40,7 @@ export function createComponentTree(props: { ...@@ -40,7 +40,7 @@ export function createComponentTree(props: {
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean authInterrupts: boolean
StreamingMetadata: React.ComponentType<{}> | null StreamingMetadata: React.ComponentType | null
StreamingMetadataOutlet: React.ComponentType StreamingMetadataOutlet: React.ComponentType
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
return getTracer().trace( return getTracer().trace(
...@@ -92,7 +92,7 @@ async function createComponentTreeInternal({ ...@@ -92,7 +92,7 @@ async function createComponentTreeInternal({
missingSlots?: Set<string> missingSlots?: Set<string>
preloadCallbacks: PreloadCallbacks preloadCallbacks: PreloadCallbacks
authInterrupts: boolean authInterrupts: boolean
StreamingMetadata: React.ComponentType<{}> | null StreamingMetadata: React.ComponentType | null
StreamingMetadataOutlet: React.ComponentType | null StreamingMetadataOutlet: React.ComponentType | null
}): Promise<CacheNodeSeedData> { }): Promise<CacheNodeSeedData> {
const { const {
......
...@@ -6,7 +6,15 @@ import { ...@@ -6,7 +6,15 @@ import {
} from '../../../shared/lib/server-inserted-metadata.shared-runtime' } from '../../../shared/lib/server-inserted-metadata.shared-runtime'
import { renderToString } from '../render-to-string' 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 metadataResolver: MetadataResolver | null = null
let metadataToFlush: React.ReactNode = null let metadataToFlush: React.ReactNode = null
const setMetadataResolver = (resolver: MetadataResolver): void => { const setMetadataResolver = (resolver: MetadataResolver): void => {
...@@ -34,7 +42,12 @@ export function createServerInsertedMetadata() { ...@@ -34,7 +42,12 @@ export function createServerInsertedMetadata() {
metadataToFlush = metadataResolver() metadataToFlush = metadataResolver()
const html = await renderToString({ const html = await renderToString({
renderToReadableStream, renderToReadableStream,
element: <>{metadataToFlush}</>, element: (
<>
{metadataToFlush}
<script nonce={nonce}>{REINSERT_ICON_SCRIPT}</script>
</>
),
}) })
return html 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 { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('app-dir - metadata-icons', () => { describe('app-dir - metadata-icons', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -28,4 +29,66 @@ describe('app-dir - metadata-icons', () => { ...@@ -28,4 +29,66 @@ describe('app-dir - metadata-icons', () => {
'/shortcut-icon-nested.png' '/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