Metadata 物件與 generateMetadata 選項
本頁涵蓋所有使用 generateMetadata
與靜態 metadata 物件的 基於設定的 Metadata 選項。
import { Metadata } from 'next'
// 靜態 metadata
export const metadata: Metadata = {
title: '...',
}
// 或動態 metadata
export async function generateMetadata({ params }) {
return {
title: '...',
}
}
// 靜態 metadata
export const metadata = {
title: '...',
}
// 或動態 metadata
export async function generateMetadata({ params }) {
return {
title: '...',
}
}
須知事項:
metadata
物件與generateMetadata
函式匯出 僅支援在伺服器元件 (Server Components) 中使用。- 您無法從同一個路由區段同時匯出
metadata
物件與generateMetadata
函式。
metadata
物件
要定義靜態 metadata,請從 layout.js
或 page.js
檔案匯出一個 Metadata
物件。
import { Metadata } from 'next'
export const metadata: Metadata = {
title: '...',
description: '...',
}
export default function Page() {}
export const metadata = {
title: '...',
description: '...',
}
export default function Page() {}
完整支援選項請參閱 Metadata 欄位。
generateMetadata
函式
動態 metadata 依賴於 動態資訊,例如當前路由參數、外部資料或父區段的 metadata
,可透過匯出一個回傳 Metadata
物件 的 generateMetadata
函式來設定。
import { Metadata, ResolvingMetadata } from 'next'
type Props = {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
// 讀取路由參數
const id = params.id
// 取得資料
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// 可選存取並擴展 (而非取代) 父 metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
openGraph: {
images: ['/some-specific-page-image.jpg', ...previousImages],
},
}
}
export default function Page({ params, searchParams }: Props) {}
export async function generateMetadata({ params, searchParams }, parent) {
// 讀取路由參數
const id = params.id
// 取得資料
const product = await fetch(`https://.../${id}`).then((res) => res.json())
// 可選存取並擴展 (而非取代) 父 metadata
const previousImages = (await parent).openGraph?.images || []
return {
title: product.title,
openGraph: {
images: ['/some-specific-page-image.jpg', ...previousImages],
},
}
}
export default function Page({ params, searchParams }) {}
參數
generateMetadata
函式接受以下參數:
-
props
- 包含當前路由參數的物件:-
params
- 包含從根區段到呼叫generateMetadata
區段的 動態路由參數 物件。範例:路由 URL params
app/shop/[slug]/page.js
/shop/1
{ slug: '1' }
app/shop/[tag]/[item]/page.js
/shop/1/2
{ tag: '1', item: '2' }
app/shop/[...slug]/page.js
/shop/1/2
{ slug: ['1', '2'] }
-
searchParams
- 包含當前 URL 的 搜尋參數 (search params) 物件。範例:URL searchParams
/shop?a=1
{ a: '1' }
/shop?a=1&b=2
{ a: '1', b: '2' }
/shop?a=1&a=2
{ a: ['1', '2'] }
-
-
parent
- 父路由區段已解析 metadata 的 Promise。
回傳值
generateMetadata
應回傳一個包含一個或多個 metadata 欄位的 Metadata
物件。
須知事項:
- 若 metadata 不依賴於執行階段資訊,應使用靜態
metadata
物件 而非generateMetadata
來定義。fetch
請求會自動在generateMetadata
、generateStaticParams
、Layouts、Pages 和 Server Components 之間 記憶化 (memoized)。若無法使用fetch
,可使用 Reactcache
。searchParams
僅在page.js
區段中可用。- Next.js 方法
redirect()
和notFound()
也可在generateMetadata
中使用。
Metadata 欄位
title
title
屬性用於設定文件的標題。可定義為簡單的 字串 或可選的 模板物件。
字串
export const metadata = {
title: 'Next.js',
}
<title>Next.js</title>
模板物件
import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '...',
default: '...',
absolute: '...',
},
}
export const metadata = {
title: {
default: '...',
template: '...',
absolute: '...',
},
}
預設值
title.default
可用於為未定義 title
的子路由區段提供 後備標題。
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: {
default: 'Acme',
},
}
import type { Metadata } from 'next'
export const metadata: Metadata = {}
// 輸出: <title>Acme</title>
模板
title.template
可用於為 子 路由區段中定義的 titles
添加前綴或後綴。
import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
default: 'Acme', // 建立模板時需提供預設值
},
}
export const metadata = {
title: {
template: '%s | Acme',
default: 'Acme', // 建立模板時需提供預設值
},
}
import { Metadata } from 'next'
export const metadata: Metadata = {
title: 'About',
}
// 輸出: <title>About | Acme</title>
export const metadata = {
title: 'About',
}
// 輸出: <title>About | Acme</title>
須知事項:
title.template
適用於 子 路由區段,而非定義它的區段。這意味著:
- 當您添加
title.template
時,title.default
是 必需的。layout.js
中定義的title.template
不會套用至相同路由區段page.js
中定義的title
。page.js
中定義的title.template
無效,因為頁面始終是路由的終止區段 (它沒有任何子路由區段)。若路由未定義
title
或title.default
,title.template
將 無效。
絕對值
title.absolute
可用於提供 忽略 父區段中設定的 title.template
的標題。
import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
template: '%s | Acme',
},
}
export const metadata = {
title: {
template: '%s | Acme',
},
}
import { Metadata } from 'next'
export const metadata: Metadata = {
title: {
absolute: 'About',
},
}
// 輸出: <title>About</title>
export const metadata = {
title: {
absolute: 'About',
},
}
// 輸出: <title>About</title>
須知事項:
layout.js
title
(字串) 和title.default
為未定義自身title
的子區段定義預設標題。若存在,它將擴展最接近父區段的title.template
。title.absolute
為子區段定義預設標題。它忽略父區段的title.template
。title.template
為子區段定義新的標題模板。
page.js
- 若頁面未定義自身標題,將使用最接近父區段的解析標題。
title
(字串) 定義路由標題。若存在,它將擴展最接近父區段的title.template
。title.absolute
定義路由標題。它忽略父區段的title.template
。title.template
在page.js
中無效,因為頁面始終是路由的終止區段。
description
export const metadata = {
description: 'The React Framework for the Web',
}
<meta name="description" content="The React Framework for the Web" />
基本欄位
export const metadata = {
generator: 'Next.js',
applicationName: 'Next.js',
referrer: 'origin-when-cross-origin',
keywords: ['Next.js', 'React', 'JavaScript'],
authors: [{ name: 'Seb' }, { name: 'Josh', url: 'https://nextjs.org' }],
creator: 'Jiachi Liu',
publisher: 'Sebastian Markbåge',
formatDetection: {
email: false,
address: false,
telephone: false,
},
}
<meta name="application-name" content="Next.js" />
<meta name="author" content="Seb" />
<link rel="author" href="https://nextjs.org" />
<meta name="author" content="Josh" />
<meta name="generator" content="Next.js" />
<meta name="keywords" content="Next.js,React,JavaScript" />
<meta name="referrer" content="origin-when-cross-origin" />
<meta name="color-scheme" content="dark" />
<meta name="creator" content="Jiachi Liu" />
<meta name="publisher" content="Sebastian Markbåge" />
<meta name="format-detection" content="telephone=no, address=no, email=no" />
metadataBase
metadataBase
是一個便利選項,用於為需要完整 URL 的 metadata
欄位設定基礎 URL 前綴。
metadataBase
允許 當前路由區段及以下 中定義的基於 URL 的metadata
欄位使用 相對路徑,而非原本需要的絕對 URL。- 欄位的相對路徑將與
metadataBase
組合形成完整 URL。 - 若未設定,
metadataBase
將 自動填充 一個 預設值。
export const metadata = {
metadataBase: new URL('https://acme.com'),
alternates: {
canonical: '/',
languages: {
'en-US': '/en-US',
'de-DE': '/de-DE',
},
},
openGraph: {
images: '/og-image.png',
},
}
<link rel="canonical" href="https://acme.com" />
<link rel="alternate" hreflang="en-US" href="https://acme.com/en-US" />
<link rel="alternate" hreflang="de-DE" href="https://acme.com/de-DE" />
<meta property="og:image" content="https://acme.com/og-image.png" />
須知事項:
metadataBase
通常設定在根app/layout.js
以應用於所有路由中基於 URL 的metadata
欄位。- 所有需要絕對 URL 的基於 URL 的
metadata
欄位都可透過metadataBase
選項設定。metadataBase
可包含子網域,例如https://app.acme.com
或基礎路徑,例如https://acme.com/start/from/here
- 若
metadata
欄位提供絕對 URL,metadataBase
將被忽略。- 在未設定
metadataBase
的情況下於基於 URL 的metadata
欄位中使用相對路徑將導致建置錯誤。- Next.js 會將
metadataBase
(例如https://acme.com/
) 與相對欄位 (例如/path
) 之間的重複斜線正規化為單一斜線 (例如https://acme.com/path
)
預設值
若未設定,metadataBase
有一個 預設值
- 當偵測到
VERCEL_URL
時:https://${process.env.VERCEL_URL}
,否則回退到http://localhost:${process.env.PORT || 3000}
。 - 當覆寫預設值時,建議使用環境變數來計算 URL。這允許為本地開發、預發佈和生產環境設定 URL。
URL 組合
URL 組合優先考慮開發者意圖而非預設的目錄遍歷語意。
metadataBase
與metadata
欄位之間的尾部斜線會被正規化。metadata
欄位中的「絕對」路徑 (通常會取代整個 URL 路徑) 會被視為「相對」路徑 (從metadataBase
的結尾開始)。
例如,給定以下 metadataBase
:
import { Metadata } from 'next'
export const metadata: Metadata = {
metadataBase: new URL('https://acme.com'),
}
export const metadata = {
metadataBase: new URL('https://acme.com'),
}
任何繼承上述 metadataBase
並設定自身值的 metadata
欄位將解析如下:
metadata 欄位 | 解析後的 URL |
---|---|
/ | https://acme.com |
./ | https://acme.com |
payments | https://acme.com/payments |
/payments | https://acme.com/payments |
./payments | https://acme.com/payments |
../payments | https://acme.com/payments |
https://beta.acme.com/payments | https://beta.acme.com/payments |
openGraph
export const metadata = {
openGraph: {
title: 'Next.js',
description: 'The React Framework for the Web',
url: 'https://nextjs.org',
siteName: 'Next.js',
images: [
{
url: 'https://nextjs.org/og.png', // 必須是絕對 URL
width: 800,
height: 600,
},
{
url: 'https://nextjs.org/og-alt.png', // 必須是絕對 URL
width: 1800,
height: 1600,
alt: '我的自訂替代文字',
},
],
videos: [
{
url: 'https://nextjs.org/video.mp4', // 必須是絕對 URL
width: 800,
height: 600,
},
],
audio: [
{
url: 'https://nextjs.org/audio.mp3', // 必須是絕對 URL
},
],
locale: 'en_US',
type: 'website',
},
}
<meta property="og:title" content="Next.js" />
<meta property="og:description" content="The React Framework for the Web" />
<meta property="og:url" content="https://nextjs.org/" />
<meta property="og:site_name" content="Next.js" />
<meta property="og:locale" content="en_US" />
<meta property="og:image:url" content="https://nextjs.org/og.png" />
<meta property="og:image:width" content="800" />
<meta property="og:image:height" content="600" />
<meta property="og:image:url" content="https://nextjs.org/og-alt.png" />
<meta property="og:image:width" content="1800" />
<meta property="og:image:height" content="1600" />
<meta property="og:image:alt" content="我的自訂替代文字" />
<meta property="og:video" content="https://nextjs.org/video.mp4" />
<meta property="og:video:width" content="800" />
<meta property="og:video:height" content="600" />
<meta property="og:audio" content="https://nextjs.org/audio.mp3" />
<meta property="og:type" content="website" />
export const metadata = {
openGraph: {
title: 'Next.js',
description: 'The React Framework for the Web',
type: 'article',
publishedTime: '2023-01-01T00:00:00.000Z',
authors: ['Seb', 'Josh'],
},
}
<meta property="og:title" content="Next.js" />
<meta property="og:description" content="The React Framework for the Web" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2023-01-01T00:00:00.000Z" />
<meta property="article:author" content="Seb" />
<meta property="article:author" content="Josh" />
小知識:
- 對於 Open Graph 圖片,使用基於檔案的 Metadata API 可能更方便。無需手動同步配置匯出與實際檔案,基於檔案的 API 會自動為您生成正確的中繼資料。
robots
import type { Metadata } from 'next'
export const metadata: Metadata = {
robots: {
index: false,
follow: true,
nocache: true,
googleBot: {
index: true,
follow: false,
noimageindex: true,
'max-video-preview': -1,
'max-image-preview': 'large',
'max-snippet': -1,
},
},
}
<meta name="robots" content="noindex, follow, nocache" />
<meta
name="googlebot"
content="index, nofollow, noimageindex, max-video-preview:-1, max-image-preview:large, max-snippet:-1"
/>
icons
小知識:我們建議盡可能使用基於檔案的 Metadata API 來設定圖示。無需手動同步配置匯出與實際檔案,基於檔案的 API 會自動為您生成正確的中繼資料。
export const metadata = {
icons: {
icon: '/icon.png',
shortcut: '/shortcut-icon.png',
apple: '/apple-icon.png',
other: {
rel: 'apple-touch-icon-precomposed',
url: '/apple-touch-icon-precomposed.png',
},
},
}
<link rel="shortcut icon" href="/shortcut-icon.png" />
<link rel="icon" href="/icon.png" />
<link rel="apple-touch-icon" href="/apple-icon.png" />
<link
rel="apple-touch-icon-precomposed"
href="/apple-touch-icon-precomposed.png"
/>
export const metadata = {
icons: {
icon: [
{ url: '/icon.png' },
new URL('/icon.png', 'https://example.com'),
{ url: '/icon-dark.png', media: '(prefers-color-scheme: dark)' },
],
shortcut: ['/shortcut-icon.png'],
apple: [
{ url: '/apple-icon.png' },
{ url: '/apple-icon-x3.png', sizes: '180x180', type: 'image/png' },
],
other: [
{
rel: 'apple-touch-icon-precomposed',
url: '/apple-touch-icon-precomposed.png',
},
],
},
}
<link rel="shortcut icon" href="/shortcut-icon.png" />
<link rel="icon" href="/icon.png" />
<link rel="icon" href="https://example.com/icon.png" />
<link rel="icon" href="/icon-dark.png" media="(prefers-color-scheme: dark)" />
<link rel="apple-touch-icon" href="/apple-icon.png" />
<link
rel="apple-touch-icon-precomposed"
href="/apple-touch-icon-precomposed.png"
/>
<link
rel="apple-touch-icon"
href="/apple-icon-x3.png"
sizes="180x180"
type="image/png"
/>
小知識:
msapplication-*
中繼標籤在 Microsoft Edge 的 Chromium 版本中已不再支援,因此不再需要。
themeColor
已棄用:
metadata
中的themeColor
選項自 Next.js 14 起已棄用。請改用viewport
配置。
manifest
網路應用程式清單,定義於網路應用程式清單規範。
export const metadata = {
manifest: 'https://nextjs.org/manifest.json',
}
<link rel="manifest" href="https://nextjs.org/manifest.json" />
twitter
Twitter 規範(令人驚訝地)不僅用於 X(前身為 Twitter)。
了解更多關於 Twitter Card 標記參考。
export const metadata = {
twitter: {
card: 'summary_large_image',
title: 'Next.js',
description: 'The React Framework for the Web',
siteId: '1467726470533754880',
creator: '@nextjs',
creatorId: '1467726470533754880',
images: ['https://nextjs.org/og.png'], // 必須是絕對 URL
},
}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site:id" content="1467726470533754880" />
<meta name="twitter:creator" content="@nextjs" />
<meta name="twitter:creator:id" content="1467726470533754880" />
<meta name="twitter:title" content="Next.js" />
<meta name="twitter:description" content="The React Framework for the Web" />
<meta name="twitter:image" content="https://nextjs.org/og.png" />
export const metadata = {
twitter: {
card: 'app',
title: 'Next.js',
description: 'The React Framework for the Web',
siteId: '1467726470533754880',
creator: '@nextjs',
creatorId: '1467726470533754880',
images: {
url: 'https://nextjs.org/og.png',
alt: 'Next.js Logo',
},
app: {
name: 'twitter_app',
id: {
iphone: 'twitter_app://iphone',
ipad: 'twitter_app://ipad',
googleplay: 'twitter_app://googleplay',
},
url: {
iphone: 'https://iphone_url',
ipad: 'https://ipad_url',
},
},
},
}
<meta name="twitter:site:id" content="1467726470533754880" />
<meta name="twitter:creator" content="@nextjs" />
<meta name="twitter:creator:id" content="1467726470533754880" />
<meta name="twitter:title" content="Next.js" />
<meta name="twitter:description" content="The React Framework for the Web" />
<meta name="twitter:card" content="app" />
<meta name="twitter:image" content="https://nextjs.org/og.png" />
<meta name="twitter:image:alt" content="Next.js Logo" />
<meta name="twitter:app:name:iphone" content="twitter_app" />
<meta name="twitter:app:id:iphone" content="twitter_app://iphone" />
<meta name="twitter:app:id:ipad" content="twitter_app://ipad" />
<meta name="twitter:app:id:googleplay" content="twitter_app://googleplay" />
<meta name="twitter:app:url:iphone" content="https://iphone_url" />
<meta name="twitter:app:url:ipad" content="https://ipad_url" />
<meta name="twitter:app:name:ipad" content="twitter_app" />
<meta name="twitter:app:name:googleplay" content="twitter_app" />
viewport
已棄用:
metadata
中的viewport
選項自 Next.js 14 起已棄用。請改用viewport
配置。
verification
export const metadata = {
verification: {
google: 'google',
yandex: 'yandex',
yahoo: 'yahoo',
other: {
me: ['my-email', 'my-link'],
},
},
}
<meta name="google-site-verification" content="google" />
<meta name="y_key" content="yahoo" />
<meta name="yandex-verification" content="yandex" />
<meta name="me" content="my-email" />
<meta name="me" content="my-link" />
appleWebApp
export const metadata = {
itunes: {
appId: 'myAppStoreID',
appArgument: 'myAppArgument',
},
appleWebApp: {
title: 'Apple Web App',
statusBarStyle: 'black-translucent',
startupImage: [
'/assets/startup/apple-touch-startup-image-768x1004.png',
{
url: '/assets/startup/apple-touch-startup-image-1536x2008.png',
media: '(device-width: 768px) and (device-height: 1024px)',
},
],
},
}
<meta
name="apple-itunes-app"
content="app-id=myAppStoreID, app-argument=myAppArgument"
/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="Apple Web App" />
<link
href="/assets/startup/apple-touch-startup-image-768x1004.png"
rel="apple-touch-startup-image"
/>
<link
href="/assets/startup/apple-touch-startup-image-1536x2008.png"
media="(device-width: 768px) and (device-height: 1024px)"
rel="apple-touch-startup-image"
/>
<meta
name="apple-mobile-web-app-status-bar-style"
content="black-translucent"
/>
alternates
export const metadata = {
alternates: {
canonical: 'https://nextjs.org',
languages: {
'en-US': 'https://nextjs.org/en-US',
'de-DE': 'https://nextjs.org/de-DE',
},
media: {
'only screen and (max-width: 600px)': 'https://nextjs.org/mobile',
},
types: {
'application/rss+xml': 'https://nextjs.org/rss',
},
},
}
<link rel="canonical" href="https://nextjs.org" />
<link rel="alternate" hreflang="en-US" href="https://nextjs.org/en-US" />
<link rel="alternate" hreflang="de-DE" href="https://nextjs.org/de-DE" />
<link
rel="alternate"
media="only screen and (max-width: 600px)"
href="https://nextjs.org/mobile"
/>
<link
rel="alternate"
type="application/rss+xml"
href="https://nextjs.org/rss"
/>
appLinks
export const metadata = {
appLinks: {
ios: {
url: 'https://nextjs.org/ios',
app_store_id: 'app_store_id',
},
android: {
package: 'com.example.android/package',
app_name: 'app_name_android',
},
web: {
url: 'https://nextjs.org/web',
should_fallback: true,
},
},
}
<meta property="al:ios:url" content="https://nextjs.org/ios" />
<meta property="al:ios:app_store_id" content="app_store_id" />
<meta property="al:android:package" content="com.example.android/package" />
<meta property="al:android:app_name" content="app_name_android" />
<meta property="al:web:url" content="https://nextjs.org/web" />
<meta property="al:web:should_fallback" content="true" />
archives
描述具有歷史價值的記錄、文件或其他材料的集合(來源)。
export const metadata = {
archives: ['https://nextjs.org/13'],
}
<link rel="archives" href="https://nextjs.org/13" />
assets
export const metadata = {
assets: ['https://nextjs.org/assets'],
}
<link rel="assets" href="https://nextjs.org/assets" />
bookmarks
export const metadata = {
bookmarks: ['https://nextjs.org/13'],
}
<link rel="bookmarks" href="https://nextjs.org/13" />
category
export const metadata = {
category: 'technology',
}
<meta name="category" content="technology" />
facebook
您可以將 Facebook 應用程式或 Facebook 帳戶連接到您的網頁,以使用某些 Facebook 社交插件 Facebook 文件
小知識:您可以指定 appId 或 admins,但不能同時指定兩者。
export const metadata = {
facebook: {
appId: '12345678',
},
}
<meta property="fb:app_id" content="12345678" />
export const metadata = {
facebook: {
admins: '12345678',
},
}
<meta property="fb:admins" content="12345678" />
如果您想生成多個 fb:admins 中繼標籤,可以使用陣列值。
export const metadata = {
facebook: {
admins: ['12345678', '87654321'],
},
}
<meta property="fb:admins" content="12345678" />
<meta property="fb:admins" content="87654321" />
other
所有中繼資料選項都應使用內建支援來涵蓋。然而,可能會有特定於您網站的自訂中繼資料標籤,或是剛發布的全新中繼資料標籤。您可以使用 other
選項來渲染任何自訂中繼資料標籤。
export const metadata = {
other: {
custom: 'meta',
},
}
<meta name="custom" content="meta" />
如果您想生成多個相同鍵的中繼標籤,可以使用陣列值。
export const metadata = {
other: {
custom: ['meta1', 'meta2'],
},
}
<meta name="custom" content="meta1" /> <meta name="custom" content="meta2" />
不支援的中繼資料類型
以下中繼資料類型目前沒有內建支援功能,但仍可直接在版面配置或頁面中渲染。
中繼資料 | 建議作法 |
---|---|
<meta http-equiv="..."> | 透過 redirect() 、中介軟體 (Middleware) 或 安全標頭 (Security Headers) 設定適當的 HTTP 標頭 |
<base> | 直接在版面配置或頁面中渲染此標籤。 |
<noscript> | 直接在版面配置或頁面中渲染此標籤。 |
<style> | 深入了解 Next.js 中的樣式設定。 |
<script> | 深入了解 指令碼使用方式。 |
<link rel="stylesheet" /> | 直接在版面配置或頁面中 import 樣式表。 |
<link rel="preload /> | 使用 ReactDOM 的 preload 方法 |
<link rel="preconnect" /> | 使用 ReactDOM 的 preconnect 方法 |
<link rel="dns-prefetch" /> | 使用 ReactDOM 的 prefetchDNS 方法 |
資源提示 (Resource Hints)
<link>
元素有多種 rel
關鍵字可用於提示瀏覽器可能需要外部資源。瀏覽器會根據這些關鍵字應用預載優化。
雖然中繼資料 API 不直接支援這些提示,但您可以使用新的 ReactDOM
方法 安全地將它們插入文件的 <head>
中。
'use client'
import ReactDOM from 'react-dom'
export function PreloadResources() {
ReactDOM.preload('...', { as: '...' })
ReactDOM.preconnect('...', { crossOrigin: '...' })
ReactDOM.prefetchDNS('...')
return null
}
'use client'
import ReactDOM from 'react-dom'
export function PreloadResources() {
ReactDOM.preload('...', { as: '...' })
ReactDOM.preconnect('...', { crossOrigin: '...' })
ReactDOM.prefetchDNS('...')
return null
}
<link rel="preload">
在頁面渲染 (瀏覽器) 生命週期早期開始載入資源。MDN 文件。
ReactDOM.preload(href: string, options: { as: string })
<link rel="preload" href="..." as="..." />
<link rel="preconnect">
預先初始化與來源的連接。MDN 文件。
ReactDOM.preconnect(href: string, options?: { crossOrigin?: string })
<link rel="preconnect" href="..." crossorigin />
<link rel="dns-prefetch">
在資源被請求前嘗試解析域名。MDN 文件。
ReactDOM.prefetchDNS(href: string)
<link rel="dns-prefetch" href="..." />
須知事項:
- 這些方法目前僅在客戶端元件 (Client Components) 中支援,初始頁面載入時仍會進行伺服器端渲染 (SSR)。
- Next.js 內建功能如
next/font
、next/image
和next/script
會自動處理相關資源提示。- React 18.3 尚未包含
ReactDOM.preload
、ReactDOM.preconnect
和ReactDOM.preconnectDNS
的類型定義。您可暫時使用// @ts-ignore
來避免類型錯誤。
類型定義
您可以使用 Metadata
類型為中繼資料添加類型安全。如果您的 IDE 使用內建 TypeScript 插件,則無需手動添加類型,但仍可明確添加。
metadata
物件
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Next.js',
}
generateMetadata
函式
常規函式
import type { Metadata } from 'next'
export function generateMetadata(): Metadata {
return {
title: 'Next.js',
}
}
非同步函式
import type { Metadata } from 'next'
export async function generateMetadata(): Promise<Metadata> {
return {
title: 'Next.js',
}
}
搭配區段屬性
import type { Metadata } from 'next'
type Props = {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}
export function generateMetadata({ params, searchParams }: Props): Metadata {
return {
title: 'Next.js',
}
}
export default function Page({ params, searchParams }: Props) {}
搭配父中繼資料
import type { Metadata, ResolvingMetadata } from 'next'
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
return {
title: 'Next.js',
}
}
JavaScript 專案
對於 JavaScript 專案,可使用 JSDoc 添加類型安全。
/** @type {import("next").Metadata} */
export const metadata = {
title: 'Next.js',
}
版本歷史
版本 | 變更內容 |
---|---|
v13.2.0 | viewport 、themeColor 和 colorScheme 已被棄用,改為使用 viewport 設定。 |
v13.2.0 | 引入 metadata 和 generateMetadata 功能。 |