跳至內容
App 路由器...函式generateMetadata

Metadata 物件和 generateMetadata 選項

此頁面涵蓋所有使用 generateMetadata 和靜態 metadata 物件的基於設定檔的 Metadata選項。

layout.tsx | page.tsx
import { Metadata } from 'next'
 
// either Static metadata
export const metadata: Metadata = {
  title: '...',
}
 
// or Dynamic metadata
export async function generateMetadata({ params }) {
  return {
    title: '...',
  }
}

須知:

  • metadata 物件和 generateMetadata 函式匯出僅支援伺服器元件
  • 您無法從同一路由區段匯出 metadata 物件和 generateMetadata 函式。

metadata 物件

若要定義靜態 metadata,請從 layout.jspage.js 檔案匯出 Metadata 物件

layout.tsx | page.tsx
import { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: '...',
  description: '...',
}
 
export default function Page() {}

請參閱 Metadata 欄位,以取得支援選項的完整清單。

generateMetadata 函數

動態元資料依賴於動態資訊,例如當前的路由參數、外部資料或父區段中的 metadata,可透過匯出 generateMetadata 函數來設定,此函數會傳回 Metadata 物件

app/products/[id]/page.tsx
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> {
  // read route params
  const id = params.id
 
  // fetch data
  const product = await fetch(`https://.../${id}`).then((res) => res.json())
 
  // optionally access and extend (rather than replace) parent 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) {}

參數

generateMetadata 函數接受下列參數

  • props - 包含當前路由參數的物件

    • params - 包含 動態路由參數 物件的物件,從根區段到呼叫 generateMetadata 的區段。範例

      路由URLparams
      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 搜尋參數 的物件。範例

      URLsearchParams
      /shop?a=1{ a: '1' }
      /shop?a=1&b=2{ a: '1', b: '2' }
      /shop?a=1&a=2{ a: ['1', '2'] }
  • parent - 父路由區段已解析的元資料承諾。

傳回

generateMetadata 應傳回一個包含一個或多個元資料欄位的 Metadata 物件

須知:

  • 如果元資料不依賴於執行時期資訊,則應使用靜態 metadata 物件 定義,而不是 generateMetadata
  • fetch 要求會自動 備忘 generateMetadatagenerateStaticParams、佈局、頁面和伺服器元件中相同的資料。如果無法使用 fetch,可以使用 React 快取
  • searchParams 僅在 page.js 區段中可用。
  • Next.js 方法 redirect()notFound() 也可用於 generateMetadata 中。

元資料欄位

title

title 屬性用於設定文件的標題。它可以定義為一個簡單的 字串 或一個選用的 範本物件

字串

layout.js | page.js
export const metadata = {
  title: 'Next.js',
}
<head> 輸出
<title>Next.js</title>

範本物件

app/layout.tsx
import { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: {
    template: '...',
    default: '...',
    absolute: '...',
  },
}
預設

title.default 可用於為未定義 title 的子路由區段提供備用標題

app/layout.tsx
import type { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: {
    default: 'Acme',
  },
}
app/about/page.tsx
import type { Metadata } from 'next'
 
export const metadata: Metadata = {}
 
// Output: <title>Acme</title>
範本

title.template 可用於為路由區段中定義的 titles 新增前綴或後綴。

app/layout.tsx
import { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: {
    template: '%s | Acme',
    default: 'Acme', // a default is required when creating a template
  },
}
app/about/page.tsx
import { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: 'About',
}
 
// Output: <title>About | Acme</title>

須知:

  • title.template 適用於路由區段,適用於它所定義的區段。這表示

    • 當您新增 title.template 時,title.default必要的
    • layout.js 中定義的 title.template 不會套用於在同一路由區段的 page.js 中定義的 title
    • page.js 中定義的 title.template 沒有作用,因為頁面永遠是終止區段(它沒有任何子路由區段)。
絕對

title.absolute 可用於提供一個標題,忽略父段落中設定的 title.template

app/layout.tsx
import { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: {
    template: '%s | Acme',
  },
}
app/about/page.tsx
import { Metadata } from 'next'
 
export const metadata: Metadata = {
  title: {
    absolute: 'About',
  },
}
 
// Output: <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.templatepage.js 中沒有作用,因為頁面總是路由的終止段落。

description

layout.js | page.js
export const metadata = {
  description: 'The React Framework for the Web',
}
<head> 輸出
<meta name="description" content="The React Framework for the Web" />

基本欄位

layout.js | page.js
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.dev.org.tw' }],
  creator: 'Jiachi Liu',
  publisher: 'Sebastian Markbåge',
  formatDetection: {
    email: false,
    address: false,
    telephone: false,
  },
}
<head> 輸出
<meta name="application-name" content="Next.js" />
<meta name="author" content="Seb" />
<link rel="author" href="https://nextjs.dev.org.tw" />
<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自動填入 預設值
layout.js | page.js
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',
  },
}
<head> 輸出
<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
  • 在 URL 型 metadata 欄位中使用相對路徑,但未設定 metadataBase,將會導致建置錯誤。
  • Next.js 會將 metadataBase(例如 https://acme.com/)和相對欄位(例如 /path)之間重複的斜線正規化為單一斜線(例如 https://acme.com/path

預設值

如果未設定,metadataBase 會有 預設值

  • 當偵測到 VERCEL_URL 時:https://${process.env.VERCEL_URL},否則會退回至 https://127.0.0.1:${process.env.PORT || 3000}
  • 覆寫預設值時,我們建議使用環境變數來計算 URL。這允許為本地開發、登台和製作環境設定 URL。

網址組成

網址組成優先考慮開發人員意圖,而非預設目錄遍歷語意。

  • metadataBasemetadata 欄位之間的尾部斜線會正規化。
  • metadata 欄位中的「絕對」路徑(通常會取代整個網址路徑)會視為「相對」路徑(從 metadataBase 的結尾開始)。

例如,給定下列 metadataBase

app/layout.tsx
import { Metadata } from 'next'
 
export const metadata: Metadata = {
  metadataBase: new URL('https://acme.com'),
}

任何繼承上述 metadataBase 並設定其自身值的 metadata 欄位,將會解析如下

metadata 欄位已解析網址
/https://acme.com
./https://acme.com
paymentshttps://acme.com/payments
/paymentshttps://acme.com/payments
./paymentshttps://acme.com/payments
../paymentshttps://acme.com/payments
https://beta.acme.com/paymentshttps://beta.acme.com/payments

openGraph

layout.js | page.js
export const metadata = {
  openGraph: {
    title: 'Next.js',
    description: 'The React Framework for the Web',
    url: 'https://nextjs.dev.org.tw',
    siteName: 'Next.js',
    images: [
      {
        url: 'https://nextjs.dev.org.tw/og.png', // Must be an absolute URL
        width: 800,
        height: 600,
      },
      {
        url: 'https://nextjs.dev.org.tw/og-alt.png', // Must be an absolute URL
        width: 1800,
        height: 1600,
        alt: 'My custom alt',
      },
    ],
    locale: 'en_US',
    type: 'website',
  },
}
<head> 輸出
<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.dev.org.tw/" />
<meta property="og:site_name" content="Next.js" />
<meta property="og:locale" content="en_US" />
<meta property="og:image:url" content="https://nextjs.dev.org.tw/og.png" />
<meta property="og:image:width" content="800" />
<meta property="og:image:height" content="600" />
<meta property="og:image:url" content="https://nextjs.dev.org.tw/og-alt.png" />
<meta property="og:image:width" content="1800" />
<meta property="og:image:height" content="1600" />
<meta property="og:image:alt" content="My custom alt" />
<meta property="og:type" content="website" />
layout.js | page.js
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'],
  },
}
<head> 輸出
<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 會自動為您產生正確的 metadata,無需將設定檔匯出與實際檔案同步。

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,
    },
  },
}
<head> 輸出
<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 會自動產生正確的 metadata,而不用同步 config 匯出與實際檔案。

layout.js | page.js
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',
    },
  },
}
<head> 輸出
<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"
/>
layout.js | page.js
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',
      },
    ],
  },
}
<head> 輸出
<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-* meta 標籤不再支援 Microsoft Edge 的 Chromium 版本,因此不再需要。

themeColor

已棄用metadata 中的 themeColor 選項已在 Next.js 14 中棄用。請改用 viewport 設定

manifest

Web 應用程式清單,如 Web 應用程式清單規格

export const metadata = {
  manifest: 'https://nextjs.dev.org.tw/manifest.json',
}
<head> 輸出
<link rel="manifest" href="https://nextjs.dev.org.tw/manifest.json" />

twitter

Twitter 規格(令人驚訝的是)不僅用於 X(以前稱為 Twitter)。

瞭解有關 Twitter 卡片標記參考 的更多資訊。

layout.js | page.js
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.dev.org.tw/og.png'], // Must be an absolute URL
  },
}
<head> 輸出
<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.dev.org.tw/og.png" />
layout.js | page.js
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.dev.org.tw/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',
      },
    },
  },
}
<head> 輸出
<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.dev.org.tw/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

layout.js | page.js
export const metadata = {
  verification: {
    google: 'google',
    yandex: 'yandex',
    yahoo: 'yahoo',
    other: {
      me: ['my-email', 'my-link'],
    },
  },
}
<head> 輸出
<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

layout.js | page.js
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)',
      },
    ],
  },
}
<head> 輸出
<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

layout.js | page.js
export const metadata = {
  alternates: {
    canonical: 'https://nextjs.dev.org.tw',
    languages: {
      'en-US': 'https://nextjs.dev.org.tw/en-US',
      'de-DE': 'https://nextjs.dev.org.tw/de-DE',
    },
    media: {
      'only screen and (max-width: 600px)': 'https://nextjs.dev.org.tw/mobile',
    },
    types: {
      'application/rss+xml': 'https://nextjs.dev.org.tw/rss',
    },
  },
}
<head> 輸出
<link rel="canonical" href="https://nextjs.dev.org.tw" />
<link rel="alternate" hreflang="en-US" href="https://nextjs.dev.org.tw/en-US" />
<link rel="alternate" hreflang="de-DE" href="https://nextjs.dev.org.tw/de-DE" />
<link
  rel="alternate"
  media="only screen and (max-width: 600px)"
  href="https://nextjs.dev.org.tw/mobile"
/>
<link
  rel="alternate"
  type="application/rss+xml"
  href="https://nextjs.dev.org.tw/rss"
/>
layout.js | page.js
export const metadata = {
  appLinks: {
    ios: {
      url: 'https://nextjs.dev.org.tw/ios',
      app_store_id: 'app_store_id',
    },
    android: {
      package: 'com.example.android/package',
      app_name: 'app_name_android',
    },
    web: {
      url: 'https://nextjs.dev.org.tw/web',
      should_fallback: true,
    },
  },
}
<head> 輸出
<meta property="al:ios:url" content="https://nextjs.dev.org.tw/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.dev.org.tw/web" />
<meta property="al:web:should_fallback" content="true" />

archives

描述具有歷史意義的記錄、文件或其他材料的集合 (來源).

layout.js | page.js
export const metadata = {
  archives: ['https://nextjs.dev.org.tw/13'],
}
<head> 輸出
<link rel="archives" href="https://nextjs.dev.org.tw/13" />

assets

layout.js | page.js
export const metadata = {
  assets: ['https://nextjs.dev.org.tw/assets'],
}
<head> 輸出
<link rel="assets" href="https://nextjs.dev.org.tw/assets" />

書籤

layout.js | page.js
export const metadata = {
  bookmarks: ['https://nextjs.dev.org.tw/13'],
}
<head> 輸出
<link rel="bookmarks" href="https://nextjs.dev.org.tw/13" />

分類

layout.js | page.js
export const metadata = {
  category: 'technology',
}
<head> 輸出
<meta name="category" content="technology" />

其他

所有元資料選項都應使用內建支援來涵蓋。但是,可能會有一些自訂的元資料標籤是特定於您的網站,或剛發布的全新元資料標籤。您可以使用 其他 選項來呈現任何自訂的元資料標籤。

layout.js | page.js
export const metadata = {
  other: {
    custom: 'meta',
  },
}
<head> 輸出
<meta name="custom" content="meta" />

如果您想要產生多個相同的金鑰元標籤,您可以使用陣列值。

layout.js | page.js
export const metadata = {
  other: {
    custom: ['meta1', 'meta2'],
  },
}
<head> 輸出
<meta name="custom" content="meta1" /> <meta name="custom" content="meta2" />

不支援的元資料

下列元資料類型目前沒有內建支援。但是,它們仍然可以在版面配置或頁面本身中呈現。

元資料建議
<meta http-equiv="...">透過 redirect()Middleware安全標頭 使用適當的 HTTP 標頭
<base>在版面配置或頁面本身中呈現標籤。
<noscript>在版面配置或頁面本身中呈現標籤。
<style>進一步了解 Next.js 中的樣式設定
<script>進一步了解 使用腳本
<link rel="stylesheet" />直接在版面配置或頁面本身中import 樣式表。
<link rel="preload />使用 ReactDOM 預載入方法
<link rel="preconnect" />使用 ReactDOM 預先連線方法
<link rel="dns-prefetch" />使用 ReactDOM 預先擷取 DNS 方法

資源提示

<link> 元素有許多 rel 關鍵字,可用於提示瀏覽器可能需要外部資源。瀏覽器會根據關鍵字使用此資訊套用預載入最佳化。

雖然 Metadata API 不直接支援這些提示,但你可以使用新的 ReactDOM 方法 將它們安全地插入文件中的 <head>

app/preload-resources.tsx
'use client'
 
import ReactDOM from 'react-dom'
 
export function PreloadResources() {
  ReactDOM.preload('...', { as: '...' })
  ReactDOM.preconnect('...', { crossOrigin: '...' })
  ReactDOM.prefetchDNS('...')
 
  return null
}

在頁面呈現(瀏覽器)生命週期中提早載入資源。 MDN 文件.

ReactDOM.preload(href: string, options: { as: string })
<head> 輸出
<link rel="preload" href="..." as="..." />

先發制人地建立與原點的連線。 MDN 文件.

ReactDOM.preconnect(href: string, options?: { crossOrigin?: string })
<head> 輸出
<link rel="preconnect" href="..." crossorigin />

在請求資源之前嘗試解析網域名稱。 MDN 文件.

ReactDOM.prefetchDNS(href: string)
<head> 輸出
<link rel="dns-prefetch" href="..." />

須知:

  • 目前這些方法僅支援於 Client Components,它們在初始頁面載入時仍然是伺服器端渲染。
  • Next.js 內建功能,例如 next/fontnext/imagenext/script 會自動處理相關資源提示。
  • React 18.3 尚未包含 ReactDOM.preload

類型

您可以使用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.0viewportthemeColorcolorScheme 已棄用,建議改用 viewport 設定
v13.2.0已推出 metadatagenerateMetadata

後續步驟

查看所有元資料 API 選項。