Unverified Commit 1482af89 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[dev] Serve static metadata from filesystem (#83460)

Current metadata files are compiled to `route.js` files. This happens
not only to metadata API (e.g., `icon.tsx`), but to static files as
well, which is unnecessary. In development, this leads to confusing logs
such as:

```
Compiled /favicon.ico in ...ms
```

Users may reasonably wonder why Next.js is "compiling" a static file.

Static files can be served directly from the filesystem, like
`_next/static/` assets. Therefore, in development, skip compilation of
static metadata files and serve them as static.

For production, we can follow up in a separate PR to skip compiling the
`route.js` files and emit static files to the dist directory, and also
serve from the filesystem there as well.

Closes [NEXT-4338](https://linear.app/vercel/issue/NEXT-4338)

---

TODO(s) to follow up:

- Fix Cache Components failing build with metadata files inside the
dynamic route.
- x-ref: [slack
thread](https://vercel.slack.com/archives/C06N3AXRQ82/p1738053808940719)

---------
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent 345450a1
......@@ -44,6 +44,15 @@ export const getExtensionRegexString = (
return `(?:\\.(${staticExtensions.join('|')})|(\\.(${dynamicExtensions.join('|')})))`
}
/**
* Matches the static metadata files, e.g. /robots.txt, /sitemap.xml, /favicon.ico, etc.
* @param appDirRelativePath the relative file path to app/
* @returns if the path is a static metadata file route
*/
export function isStaticMetadataFile(appDirRelativePath: string) {
return isMetadataRouteFile(appDirRelativePath, [], true)
}
/**
* Determine if the file is a metadata route file entry
* @param appDirRelativePath the relative file path to app/
......
......@@ -45,6 +45,7 @@ import { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route
import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { PrefetchRSCPathnameNormalizer } from '../../normalizers/request/prefetch-rsc'
import { encodeURIPath } from '../../../shared/lib/encode-uri-path'
import { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'
export type FsOutput = {
type:
......@@ -130,6 +131,15 @@ export async function setupFsCheck(opts: {
const appFiles = new Set<string>()
const pageFiles = new Set<string>()
// Map normalized path to the file path. This is essential
// for parallel and group routes as their original path
// cannot be restored from the request path.
// Example:
// [normalized-path] -> [file-path]
// /icon-<hash>.png -> .../app/@parallel/icon.png
// /icon-<hash>.png -> .../app/(group)/icon.png
// /icon.png -> .../app/icon.png
const staticMetadataFiles = new Map<string, string>()
let dynamicRoutes: FilesystemDynamicRoute[] = []
let middlewareMatcher:
......@@ -430,6 +440,7 @@ export async function setupFsCheck(opts: {
appFiles,
pageFiles,
staticMetadataFiles,
dynamicRoutes,
nextDataRoutes,
......@@ -496,6 +507,18 @@ export async function setupFsCheck(opts: {
}
}
if (opts.dev && isMetadataRouteFile(itemPath, [], false)) {
const fsPath = staticMetadataFiles.get(itemPath)
if (fsPath) {
return {
// "nextStaticFolder" sets Cache-Control "no-store" on dev.
type: 'nextStaticFolder',
fsPath,
itemPath: fsPath,
}
}
}
const itemsToCheck: Array<[Set<string>, FsOutput['type']]> = [
[this.devVirtualFsItems, 'devVirtualFsItem'],
[nextStaticFolderItems, 'nextStaticFolder'],
......
......@@ -61,7 +61,10 @@ import type { LazyRenderServerInstance } from '../router-server'
import { HMR_MESSAGE_SENT_TO_BROWSER } from '../../dev/hot-reloader-types'
import { PAGE_TYPES } from '../../../lib/page-types'
import { generateEncryptionKeyBase64 } from '../../app-render/encryption-utils-server'
import { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'
import {
isMetadataRouteFile,
isStaticMetadataFile,
} from '../../../lib/metadata/is-metadata-route'
import { normalizeMetadataPageToRoute } from '../../../lib/metadata/get-metadata-route'
import { createEnvDefinitions } from '../experimental/create-env-definitions'
import { JsConfigPathsPlugin } from '../../../build/webpack/plugins/jsconfig-paths-plugin'
......@@ -374,10 +377,11 @@ async function startWatcher(
let conflictingPageChange = 0
let hasRootAppNotFound = false
const { appFiles, pageFiles } = opts.fsChecker
const { appFiles, pageFiles, staticMetadataFiles } = opts.fsChecker
appFiles.clear()
pageFiles.clear()
staticMetadataFiles.clear()
devPageFiles.clear()
const sortedKnownFiles: string[] = [...knownFiles.keys()].sort(
......@@ -610,7 +614,12 @@ async function startWatcher(
)
if (useFileSystemPublicRoutes) {
appFiles.add(pageName)
// Static metadata files will be served from filesystem.
if (appDir && isStaticMetadataFile(fileName.replace(appDir, ''))) {
staticMetadataFiles.set(pageName, fileName)
} else {
appFiles.add(pageName)
}
}
if (validFileMatcher.isAppRouterRoute(fileName)) {
......
......@@ -8,6 +8,7 @@ import { DevAppNormalizers } from '../../normalizers/built/app'
import {
isMetadataRouteFile,
isStaticMetadataRoute,
isStaticMetadataFile,
} from '../../../lib/metadata/is-metadata-route'
import { normalizeMetadataPageToRoute } from '../../../lib/metadata/get-metadata-route'
import path from '../../../shared/lib/isomorphic/path'
......@@ -39,6 +40,11 @@ export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvid
): Promise<ReadonlyArray<AppRouteRouteMatcher>> {
const matchers: Array<AppRouteRouteMatcher> = []
for (const filename of files) {
// Skip static metadata files as they are served from filesystem.
if (isStaticMetadataFile(filename.replace(this.appDir, ''))) {
continue
}
let page = this.normalizers.page.normalize(filename)
// If the file isn't a match for this matcher, then skip it.
......@@ -114,7 +120,7 @@ export class DevAppRouteRouteMatcherProvider extends FileCacheRouteMatcherProvid
matchers.push(matcher)
}
} else {
// Normal app routes and static metadata routes.
// Normal app routes.
matchers.push(
new AppRouteRouteMatcher({
kind: RouteKind.APP_ROUTE,
......
export default function Page() {
return <p>group</p>
}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://nextjs.org</loc>
<lastmod>2025-01-01T00:00:00.000Z</lastmod>
</url>
</urlset>
\ No newline at end of file
import { ImageResponse } from 'next/og'
export const size = {
width: 32,
height: 32,
}
export const contentType = 'image/png'
export default function Icon() {
return new ImageResponse(<div>A</div>)
}
import { ImageResponse } from 'next/og'
export const size = {
width: 32,
height: 32,
}
export const contentType = 'image/png'
export default function Icon() {
return new ImageResponse(<div>A</div>)
}
import { ImageResponse } from 'next/og'
export const size = {
width: 32,
height: 32,
}
export const contentType = 'image/png'
export default function Icon() {
return new ImageResponse(<div>A</div>)
}
import { ImageResponse } from 'next/og'
export function GET() {
return new ImageResponse(<div>A</div>)
}
import { ImageResponse } from 'next/og'
export function GET() {
return new ImageResponse(<div>A</div>)
}
import { ImageResponse } from 'next/og'
export function GET() {
return new ImageResponse(<div>A</div>)
}
export function GET() {
return new Response(
`
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://nextjs.org</loc>
<lastmod>2025-01-01T00:00:00.000Z</lastmod>
</url>
</urlset>
`.trim(),
{
headers: {
'Content-Type': 'application/xml',
},
}
)
}
import { ImageResponse } from 'next/og'
export function GET() {
return new ImageResponse(<div>A</div>)
}
import type { MetadataRoute } from 'next'
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: 'https://nextjs.org',
lastModified: '2025-01-01T00:00:00.000Z',
changeFrequency: 'monthly',
priority: 0.8,
},
]
}
import { ImageResponse } from 'next/og'
export const size = {
width: 32,
height: 32,
}
export const contentType = 'image/png'
export default function Icon() {
return new ImageResponse(<div>A</div>)
}
export default function Page() {
return <p>dynamic</p>
}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://nextjs.org</loc>
<lastmod>2025-01-01T00:00:00.000Z</lastmod>
</url>
</urlset>
\ No newline at end of file
export default function Page() {
return <p>intercept me</p>
}
export default function Page() {
return <p>intercepting</p>
}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://nextjs.org</loc>
<lastmod>2025-01-01T00:00:00.000Z</lastmod>
</url>
</urlset>
\ No newline at end of file
import Link from 'next/link'
export default function Page() {
return (
<div>
<Link href="/intercept-me">go to /intercept-me</Link>
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
{
"name": "My Next.js Application",
"short_name": "Next.js App",
"description": "An application built with Next.js",
"start_url": "/"
}
export default function Page() {
return <p>hello world</p>
}
export default function Page() {
return <p>@parallel</p>
}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://nextjs.org</loc>
<lastmod>2025-01-01T00:00:00.000Z</lastmod>
</url>
</urlset>
\ No newline at end of file
export default function ParallelLayout({
children,
parallel,
}: {
children: React.ReactNode
parallel: React.ReactNode
}) {
return (
<div>
<p>parallel</p>
{parallel}
<p>children</p>
{children}
</div>
)
}
export default function Page() {
return <p>parallel</p>
}
User-Agent: *
Allow: /
Disallow: /private/
Sitemap: https://nextjs.org/sitemap.xml
\ No newline at end of file
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://nextjs.org</loc>
<lastmod>2025-01-01T00:00:00.000Z</lastmod>
</url>
</urlset>
\ No newline at end of file
export default function Page() {
return <p>static</p>
}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://nextjs.org</loc>
<lastmod>2025-01-01T00:00:00.000Z</lastmod>
</url>
</urlset>
\ No newline at end of file
import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils'
describe('metadata-files-static-output-dynamic-route', () => {
if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS) {
// Cache Components build fails when metadata files are inside a dynamic route.
//
// Route "/dynamic/[id]" has a `generateMetadata` that depends on Request data (`cookies()`, etc...)
// or uncached external data (`fetch(...)`, etc...) when the rest of the route does not.
// See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata
// Error occurred prerendering page "/dynamic/[id]". Read more: https://nextjs.org/docs/messages/prerender-error
// Export encountered an error on /dynamic/[id]/page: /dynamic/[id], exiting the build.
//
// TODO: Remove this skip when metadata files are supported in dynamic routes for Cache Components.
it.skip('should skip test for Cache Components', () => {})
return
}
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should have correct link tags for dynamic page', async () => {
const browser = await next.browser('/dynamic/123')
expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`
{
"links": [
{
"href": "/dynamic/123/apple-icon.png",
"rel": "apple-touch-icon",
"type": "image/png",
},
{
"href": "/dynamic/123/icon.png",
"rel": "icon",
"type": "image/png",
},
{
"href": "/favicon.ico",
"rel": "icon",
"type": "image/x-icon",
},
{
"href": "/manifest.json",
"rel": "manifest",
},
],
"metas": [
{
"name": "twitter:card",
},
{
"name": "twitter:image",
},
{
"name": "twitter:image:height",
},
{
"name": "twitter:image:type",
},
{
"name": "twitter:image:width",
},
{
"name": "viewport",
},
{
"property": "og:image",
},
{
"property": "og:image:height",
},
{
"property": "og:image:type",
},
{
"property": "og:image:width",
},
],
}
`)
})
it('should serve static files when requested to its route for dynamic page', async () => {
const [
appleIconRes,
iconRes,
opengraphImageRes,
twitterImageRes,
sitemapRes,
] = await Promise.all([
next.fetch('/dynamic/123/apple-icon.png'),
next.fetch('/dynamic/123/icon.png'),
next.fetch('/dynamic/123/opengraph-image.png'),
next.fetch('/dynamic/123/twitter-image.png'),
next.fetch('/dynamic/123/sitemap.xml'),
])
// Compare response content with actual files
const [
actualAppleIcon,
actualIcon,
actualOpengraphImage,
actualTwitterImage,
actualSitemap,
] = await Promise.all([
next.readFileBuffer('app/dynamic/[id]/apple-icon.png'),
next.readFileBuffer('app/dynamic/[id]/icon.png'),
next.readFileBuffer('app/dynamic/[id]/opengraph-image.png'),
next.readFileBuffer('app/dynamic/[id]/twitter-image.png'),
next.readFile('app/dynamic/[id]/sitemap.xml'),
])
expect({
appleIcon: Buffer.compare(
Buffer.from(await appleIconRes.arrayBuffer()),
actualAppleIcon
),
icon: Buffer.compare(
Buffer.from(await iconRes.arrayBuffer()),
actualIcon
),
opengraphImage: Buffer.compare(
Buffer.from(await opengraphImageRes.arrayBuffer()),
actualOpengraphImage
),
twitterImage: Buffer.compare(
Buffer.from(await twitterImageRes.arrayBuffer()),
actualTwitterImage
),
sitemap: await sitemapRes.text(),
}).toEqual({
// Buffer comparison returns 0 for equal
appleIcon: 0,
icon: 0,
opengraphImage: 0,
twitterImage: 0,
sitemap: actualSitemap,
})
})
})
import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils'
describe('metadata-files-static-output-group-route', () => {
if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS) {
// Cache Components build fails when metadata files are inside a dynamic route.
//
// Route "/dynamic/[id]" has a `generateMetadata` that depends on Request data (`cookies()`, etc...)
// or uncached external data (`fetch(...)`, etc...) when the rest of the route does not.
// See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata
// Error occurred prerendering page "/dynamic/[id]". Read more: https://nextjs.org/docs/messages/prerender-error
// Export encountered an error on /dynamic/[id]/page: /dynamic/[id], exiting the build.
//
// TODO: Remove this skip when metadata files are supported in dynamic routes for Cache Components.
it.skip('should skip test for Cache Components', () => {})
return
}
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should have correct link tags for group page', async () => {
const browser = await next.browser('/group')
expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`
{
"links": [
{
"href": "/favicon.ico",
"rel": "icon",
"type": "image/x-icon",
},
{
"href": "/group/apple-icon-131tc6.png",
"rel": "apple-touch-icon",
"type": "image/png",
},
{
"href": "/group/icon-131tc6.png",
"rel": "icon",
"type": "image/png",
},
{
"href": "/manifest.json",
"rel": "manifest",
},
],
"metas": [
{
"name": "twitter:card",
},
{
"name": "twitter:image",
},
{
"name": "twitter:image:height",
},
{
"name": "twitter:image:type",
},
{
"name": "twitter:image:width",
},
{
"name": "viewport",
},
{
"property": "og:image",
},
{
"property": "og:image:height",
},
{
"property": "og:image:type",
},
{
"property": "og:image:width",
},
],
}
`)
})
it('should serve static files when requested to its route for group page', async () => {
const [
appleIconRes,
iconRes,
opengraphImageRes,
twitterImageRes,
sitemapRes,
] = await Promise.all([
next.fetch(`/group/apple-icon-131tc6.png`),
next.fetch(`/group/icon-131tc6.png`),
next.fetch(`/group/opengraph-image-131tc6.png`),
next.fetch(`/group/twitter-image-131tc6.png`),
next.fetch('/group/sitemap.xml'),
])
// Compare response content with actual files
const [
actualAppleIcon,
actualIcon,
actualOpengraphImage,
actualTwitterImage,
actualSitemap,
] = await Promise.all([
next.readFileBuffer('app/(group)/group/apple-icon.png'),
next.readFileBuffer('app/(group)/group/icon.png'),
next.readFileBuffer('app/(group)/group/opengraph-image.png'),
next.readFileBuffer('app/(group)/group/twitter-image.png'),
next.readFile('app/(group)/group/sitemap.xml'),
])
expect({
appleIcon: Buffer.compare(
Buffer.from(await appleIconRes.arrayBuffer()),
actualAppleIcon
),
icon: Buffer.compare(
Buffer.from(await iconRes.arrayBuffer()),
actualIcon
),
opengraphImage: Buffer.compare(
Buffer.from(await opengraphImageRes.arrayBuffer()),
actualOpengraphImage
),
twitterImage: Buffer.compare(
Buffer.from(await twitterImageRes.arrayBuffer()),
actualTwitterImage
),
sitemap: await sitemapRes.text(),
}).toEqual({
// Buffer comparison returns 0 for equal
appleIcon: 0,
icon: 0,
opengraphImage: 0,
twitterImage: 0,
sitemap: actualSitemap,
})
})
})
import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils'
describe('metadata-files-static-output-intercepting-route', () => {
if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS) {
// Cache Components build fails when metadata files are inside a dynamic route.
//
// Route "/dynamic/[id]" has a `generateMetadata` that depends on Request data (`cookies()`, etc...)
// or uncached external data (`fetch(...)`, etc...) when the rest of the route does not.
// See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata
// Error occurred prerendering page "/dynamic/[id]". Read more: https://nextjs.org/docs/messages/prerender-error
// Export encountered an error on /dynamic/[id]/page: /dynamic/[id], exiting the build.
//
// TODO: Remove this skip when metadata files are supported in dynamic routes for Cache Components.
it.skip('should skip test for Cache Components', () => {})
return
}
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should have correct link tags for intercepting page', async () => {
const browser = await next.browser('/intercepting')
// Click the link to navigate to the intercepted route
await browser.elementByCss('a[href="/intercept-me"]').click()
await browser.waitForCondition(
'window.location.pathname === "/intercept-me"'
)
expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`
{
"links": [
{
"href": "/favicon.ico",
"rel": "icon",
"type": "image/x-icon",
},
{
"href": "/intercepting/(..)intercept-me/apple-icon.png",
"rel": "apple-touch-icon",
"type": "image/png",
},
{
"href": "/intercepting/(..)intercept-me/icon.png",
"rel": "icon",
"type": "image/png",
},
{
"href": "/manifest.json",
"rel": "manifest",
},
],
"metas": [
{
"name": "twitter:card",
},
{
"name": "twitter:image",
},
{
"name": "twitter:image:height",
},
{
"name": "twitter:image:type",
},
{
"name": "twitter:image:width",
},
{
"name": "viewport",
},
{
"property": "og:image",
},
{
"property": "og:image:height",
},
{
"property": "og:image:type",
},
{
"property": "og:image:width",
},
],
}
`)
})
it('should serve static files when requested to its route for intercepting page', async () => {
const [
appleIconRes,
iconRes,
opengraphImageRes,
twitterImageRes,
sitemapRes,
] = await Promise.all([
next.fetch(`/intercepting/(..)intercept-me/apple-icon.png`),
next.fetch(`/intercepting/(..)intercept-me/icon.png`),
next.fetch(`/intercepting/(..)intercept-me/opengraph-image.png`),
next.fetch(`/intercepting/(..)intercept-me/twitter-image.png`),
next.fetch('/intercepting/(..)intercept-me/sitemap.xml'),
])
// Compare response content with actual files
const [
actualAppleIcon,
actualIcon,
actualOpengraphImage,
actualTwitterImage,
actualSitemap,
] = await Promise.all([
next.readFileBuffer('app/intercepting/(..)intercept-me/apple-icon.png'),
next.readFileBuffer('app/intercepting/(..)intercept-me/icon.png'),
next.readFileBuffer(
'app/intercepting/(..)intercept-me/opengraph-image.png'
),
next.readFileBuffer(
'app/intercepting/(..)intercept-me/twitter-image.png'
),
next.readFile('app/intercepting/(..)intercept-me/sitemap.xml'),
])
expect({
appleIcon: Buffer.compare(
Buffer.from(await appleIconRes.arrayBuffer()),
actualAppleIcon
),
icon: Buffer.compare(
Buffer.from(await iconRes.arrayBuffer()),
actualIcon
),
opengraphImage: Buffer.compare(
Buffer.from(await opengraphImageRes.arrayBuffer()),
actualOpengraphImage
),
twitterImage: Buffer.compare(
Buffer.from(await twitterImageRes.arrayBuffer()),
actualTwitterImage
),
sitemap: await sitemapRes.text(),
}).toEqual({
// Buffer comparison returns 0 for equal
appleIcon: 0,
icon: 0,
opengraphImage: 0,
twitterImage: 0,
sitemap: actualSitemap,
})
})
})
import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils'
describe('metadata-files-static-output-parallel-route', () => {
if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS) {
// Cache Components build fails when metadata files are inside a dynamic route.
//
// Route "/dynamic/[id]" has a `generateMetadata` that depends on Request data (`cookies()`, etc...)
// or uncached external data (`fetch(...)`, etc...) when the rest of the route does not.
// See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata
// Error occurred prerendering page "/dynamic/[id]". Read more: https://nextjs.org/docs/messages/prerender-error
// Export encountered an error on /dynamic/[id]/page: /dynamic/[id], exiting the build.
//
// TODO: Remove this skip when metadata files are supported in dynamic routes for Cache Components.
it.skip('should skip test for Cache Components', () => {})
return
}
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should have correct link tags for parallel slot page', async () => {
const browser = await next.browser('/parallel')
expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`
{
"links": [
{
"href": "/favicon.ico",
"rel": "icon",
"type": "image/x-icon",
},
{
"href": "/manifest.json",
"rel": "manifest",
},
{
"href": "/parallel/apple-icon-kzjltp.png",
"rel": "apple-touch-icon",
"type": "image/png",
},
{
"href": "/parallel/icon-kzjltp.png",
"rel": "icon",
"type": "image/png",
},
],
"metas": [
{
"name": "twitter:card",
},
{
"name": "twitter:image",
},
{
"name": "twitter:image:height",
},
{
"name": "twitter:image:type",
},
{
"name": "twitter:image:width",
},
{
"name": "viewport",
},
{
"property": "og:image",
},
{
"property": "og:image:height",
},
{
"property": "og:image:type",
},
{
"property": "og:image:width",
},
],
}
`)
})
it('should serve static files when requested to its route for parallel slot page', async () => {
const [
appleIconRes,
iconRes,
opengraphImageRes,
twitterImageRes,
sitemapRes,
] = await Promise.all([
next.fetch(`/parallel/apple-icon-kzjltp.png`),
next.fetch(`/parallel/icon-kzjltp.png`),
next.fetch(`/parallel/opengraph-image-kzjltp.png`),
next.fetch(`/parallel/twitter-image-kzjltp.png`),
next.fetch(`/parallel/sitemap.xml`),
])
// Compare response content with actual files
const [
actualAppleIcon,
actualIcon,
actualOpengraphImage,
actualTwitterImage,
actualSitemap,
] = await Promise.all([
next.readFileBuffer('app/parallel/@parallel/apple-icon.png'),
next.readFileBuffer('app/parallel/@parallel/icon.png'),
next.readFileBuffer('app/parallel/@parallel/opengraph-image.png'),
next.readFileBuffer('app/parallel/@parallel/twitter-image.png'),
next.readFile('app/parallel/@parallel/sitemap.xml'),
])
expect({
appleIcon: Buffer.compare(
Buffer.from(await appleIconRes.arrayBuffer()),
actualAppleIcon
),
icon: Buffer.compare(
Buffer.from(await iconRes.arrayBuffer()),
actualIcon
),
opengraphImage: Buffer.compare(
Buffer.from(await opengraphImageRes.arrayBuffer()),
actualOpengraphImage
),
twitterImage: Buffer.compare(
Buffer.from(await twitterImageRes.arrayBuffer()),
actualTwitterImage
),
sitemap: await sitemapRes.text(),
}).toEqual({
// Buffer comparison returns 0 for equal
appleIcon: 0,
icon: 0,
opengraphImage: 0,
twitterImage: 0,
sitemap: actualSitemap,
})
})
})
import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils'
describe('metadata-files-static-output-root-route', () => {
if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS) {
// Cache Components build fails when metadata files are inside a dynamic route.
//
// Route "/dynamic/[id]" has a `generateMetadata` that depends on Request data (`cookies()`, etc...)
// or uncached external data (`fetch(...)`, etc...) when the rest of the route does not.
// See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata
// Error occurred prerendering page "/dynamic/[id]". Read more: https://nextjs.org/docs/messages/prerender-error
// Export encountered an error on /dynamic/[id]/page: /dynamic/[id], exiting the build.
//
// TODO: Remove this skip when metadata files are supported in dynamic routes for Cache Components.
it.skip('should skip test for Cache Components', () => {})
return
}
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should have correct link tags for root page', async () => {
const browser = await next.browser('/')
expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`
{
"links": [
{
"href": "/favicon.ico",
"rel": "icon",
"type": "image/x-icon",
},
{
"href": "/manifest.json",
"rel": "manifest",
},
],
"metas": [
{
"name": "viewport",
},
],
}
`)
})
it('should serve static files when requested to its route', async () => {
const [faviconRes, manifestRes, robotsRes, sitemapRes] = await Promise.all([
next.fetch('/favicon.ico'),
next.fetch('/manifest.json'),
next.fetch('/robots.txt'),
next.fetch('/sitemap.xml'),
])
// Compare response content with actual files
const [actualFavicon, actualManifest, actualRobots, actualSitemap] =
await Promise.all([
next.readFileBuffer('app/favicon.ico'),
next.readFile('app/manifest.json'),
next.readFile('app/robots.txt'),
next.readFile('app/sitemap.xml'),
])
expect({
favicon: Buffer.compare(
Buffer.from(await faviconRes.arrayBuffer()),
actualFavicon
),
manifest: await manifestRes.text(),
robots: await robotsRes.text(),
sitemap: await sitemapRes.text(),
}).toEqual({
favicon: 0, // Buffer comparison returns 0 for equal
manifest: actualManifest,
robots: actualRobots,
sitemap: actualSitemap,
})
})
})
import { nextTestSetup } from 'e2e-utils'
import { getCommonMetadataHeadTags } from './utils'
describe('metadata-files-static-output-static-route', () => {
if (process.env.__NEXT_EXPERIMENTAL_CACHE_COMPONENTS) {
// Cache Components build fails when metadata files are inside a dynamic route.
//
// Route "/dynamic/[id]" has a `generateMetadata` that depends on Request data (`cookies()`, etc...)
// or uncached external data (`fetch(...)`, etc...) when the rest of the route does not.
// See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata
// Error occurred prerendering page "/dynamic/[id]". Read more: https://nextjs.org/docs/messages/prerender-error
// Export encountered an error on /dynamic/[id]/page: /dynamic/[id], exiting the build.
//
// TODO: Remove this skip when metadata files are supported in dynamic routes for Cache Components.
it.skip('should skip test for Cache Components', () => {})
return
}
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should have correct link tags for static page', async () => {
const browser = await next.browser('/static')
expect(await getCommonMetadataHeadTags(browser)).toMatchInlineSnapshot(`
{
"links": [
{
"href": "/favicon.ico",
"rel": "icon",
"type": "image/x-icon",
},
{
"href": "/manifest.json",
"rel": "manifest",
},
{
"href": "/static/apple-icon.png",
"rel": "apple-touch-icon",
"type": "image/png",
},
{
"href": "/static/icon.png",
"rel": "icon",
"type": "image/png",
},
],
"metas": [
{
"name": "twitter:card",
},
{
"name": "twitter:image",
},
{
"name": "twitter:image:height",
},
{
"name": "twitter:image:type",
},
{
"name": "twitter:image:width",
},
{
"name": "viewport",
},
{
"property": "og:image",
},
{
"property": "og:image:height",
},
{
"property": "og:image:type",
},
{
"property": "og:image:width",
},
],
}
`)
})
it('should serve static files when requested to its route for static page', async () => {
const [
appleIconRes,
iconRes,
opengraphImageRes,
twitterImageRes,
sitemapRes,
] = await Promise.all([
next.fetch('/static/apple-icon.png'),
next.fetch('/static/icon.png'),
next.fetch('/static/opengraph-image.png'),
next.fetch('/static/twitter-image.png'),
next.fetch('/static/sitemap.xml'),
])
// Compare response content with actual files
const [
actualAppleIcon,
actualIcon,
actualOpengraphImage,
actualTwitterImage,
actualSitemap,
] = await Promise.all([
next.readFileBuffer('app/static/apple-icon.png'),
next.readFileBuffer('app/static/icon.png'),
next.readFileBuffer('app/static/opengraph-image.png'),
next.readFileBuffer('app/static/twitter-image.png'),
next.readFile('app/static/sitemap.xml'),
])
expect({
appleIcon: Buffer.compare(
Buffer.from(await appleIconRes.arrayBuffer()),
actualAppleIcon
),
icon: Buffer.compare(
Buffer.from(await iconRes.arrayBuffer()),
actualIcon
),
opengraphImage: Buffer.compare(
Buffer.from(await opengraphImageRes.arrayBuffer()),
actualOpengraphImage
),
twitterImage: Buffer.compare(
Buffer.from(await twitterImageRes.arrayBuffer()),
actualTwitterImage
),
sitemap: await sitemapRes.text(),
}).toEqual({
// Buffer comparison returns 0 for equal
appleIcon: 0,
icon: 0,
opengraphImage: 0,
twitterImage: 0,
sitemap: actualSitemap,
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
// @ts-nocheck - On isolated test, this will be a type error.
import type { Playwright } from '../../../lib/next-webdriver'
async function getMetadataLinks(browser: Playwright) {
const links = await browser.locator('link').evaluateAll((elements: any[]) => {
return elements
.filter((el) => {
if (el.href.includes('/_next/static')) {
return false
}
return [
'/favicon.ico',
'/manifest.json',
'/manifest.webmanifest',
// Below may have suffixes like /icon1.png, /icon2.png, etc.
// Or has suffixes like /icon-xxxxxx.png, /icon-image-yyyyyy.jpg, etc.
'/icon',
'/apple-icon',
'/opengraph-image',
'/twitter-image',
].some((file) =>
new URL(el.href, window.location.origin).pathname.includes(file)
)
})
.map((el) => ({
href: new URL(el.href, window.location.origin).pathname,
rel: el.rel,
...(el.type && { type: el.type }),
}))
.sort((a, b) => a.href.localeCompare(b.href))
})
return links
}
async function getMetadataMetas(browser: Playwright) {
const metas = await browser.locator('meta').evaluateAll((elements: any[]) => {
return elements
.filter((meta) => {
if (!meta.name && !meta.hasAttribute('property')) {
return false
}
const attr = meta.name || meta.getAttribute('property') || ''
return [
'og:',
'twitter:',
'viewport',
'description',
'keywords',
'robots',
].some(
(prefix) => attr.startsWith(prefix) || attr === prefix.slice(0, -1)
)
})
.map((el) => ({
...(el.name && { name: el.name }),
...(el.hasAttribute('property') && {
property: el.getAttribute('property'),
}),
}))
.sort((a, b) => {
if (a.name && !b.name) return -1
if (!a.name && b.name) return 1
return (a.name || a.property || '').localeCompare(
b.name || b.property || ''
)
})
})
return metas
}
export async function getCommonMetadataHeadTags(browser: Playwright) {
const [links, metas] = await Promise.all([
getMetadataLinks(browser),
getMetadataMetas(browser),
])
return { links, metas }
}
......@@ -680,7 +680,9 @@ describe('app dir - metadata', () => {
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('image/x-icon')
expect(res.headers.get('cache-control')).toBe(
isNextDev ? 'no-cache, no-store' : 'public, max-age=0, must-revalidate'
isNextDev
? 'no-store, must-revalidate'
: 'public, max-age=0, must-revalidate'
)
})
......@@ -693,18 +695,25 @@ describe('app dir - metadata', () => {
expect(resAppleIcon.status).toBe(200)
expect(resAppleIcon.headers.get('content-type')).toBe('image/png')
expect(resAppleIcon.headers.get('cache-control')).toBe(
isNextDev ? 'no-cache, no-store' : 'public, max-age=0, must-revalidate'
isNextDev
? 'no-store, must-revalidate'
: 'public, max-age=0, must-revalidate'
)
expect(resIcon.status).toBe(200)
expect(resIcon.headers.get('content-type')).toBe('image/png')
expect(resIcon.headers.get('cache-control')).toBe(
isNextDev ? 'no-cache, no-store' : 'public, max-age=0, must-revalidate'
isNextDev
? 'no-store, must-revalidate'
: 'public, max-age=0, must-revalidate'
)
})
it('should support root dir robots.txt', async () => {
const res = await next.fetch('/robots.txt')
expect(res.headers.get('content-type')).toBe('text/plain')
expect(res.headers.get('content-type')).toBe(
// In dev, sendStatic() is used to send static files, which adds MIME type.
isNextDev ? 'text/plain; charset=UTF-8' : 'text/plain'
)
expect(await res.text()).toContain('User-Agent: *\nDisallow:')
const invalidRobotsResponse = await next.fetch('/title/robots.txt')
expect(invalidRobotsResponse.status).toBe(404)
......
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