generateMetadata
Learn how to add Metadata to your Next.js application for improved search engine optimization (SEO) and web shareability.
You can use the metadata object or the generateMetadata function to define metadata.
The metadata object
To define static metadata, export a Metadata object from a layout.js or page.js file.
See the Metadata Fields for a complete list of supported options.
generateMetadata function
Dynamic metadata depends on dynamic information, such as the current route parameters, external data, or metadata in parent segments, can be set by exporting a generateMetadata function that returns a Metadata object.
Resolving generateMetadata is part of rendering the page. If the page can be pre-rendered and generateMetadata doesn't introduce dynamic behavior, the resulting metadata is included in the page’s initial HTML.
Otherwise the metadata resolved from generateMetadata can be streamed after sending the initial UI.
For type completion of params and searchParams, you can type the first argument with PageProps<'/route'> or LayoutProps<'/route'> for pages and layouts respectively.
Good to know:
- Metadata can be added to
layout.jsandpage.jsfiles. - Next.js will automatically resolve the metadata, and create the relevant
<head>tags for the page. - The
metadataobject andgenerateMetadatafunction exports are only supported in Server Components. - You cannot export both the
metadataobject andgenerateMetadatafunction from the same route segment. fetchrequests insidegenerateMetadataare automatically memoized for the same data acrossgenerateMetadata,generateStaticParams, Layouts, Pages, and Server Components.- React
cachecan be used iffetchis unavailable. - File-based metadata has the higher priority and will override the
metadataobject andgenerateMetadatafunction.
Reference
Parameters
generateMetadata function accepts the following parameters:
-
props- An object containing the parameters of the current route:-
params- An object containing the dynamic route parameters object from the root segment down to the segmentgenerateMetadatais called from. Examples:Route URL paramsapp/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- An object containing the current URL's search params. Examples: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- A promise of the resolved metadata from parent route segments.
Returns
generateMetadata should return a Metadata object containing one or more metadata fields.
Good to know:
- If metadata doesn't depend on runtime information, it should be defined using the static
metadataobject rather thangenerateMetadata. fetchrequests are automatically memoized for the same data acrossgenerateMetadata,generateStaticParams, Layouts, Pages, and Server Components. Reactcachecan be used iffetchis unavailable.searchParamsare only available inpage.jssegments.- The
redirect()andnotFound()Next.js methods can also be used insidegenerateMetadata.
Metadata Fields
The following fields are supported:
title
The title attribute is used to set the title of the document. It can be defined as a simple string or an optional template object.
String
default
title.default can be used to provide a fallback title to child route segments that don't define a title.
template
title.template can be used to add a prefix or a suffix to titles defined in child route segments.
Good to know:
title.templateapplies to child route segments and not the segment it's defined in. This means:title.defaultis required when you add atitle.template.title.templatedefined inlayout.jswill not apply to atitledefined in apage.jsof the same route segment.title.templatedefined inpage.jshas no effect because a page is always the terminating segment (it doesn't have any children route segments).
title.templatehas no effect if a route has not defined atitleortitle.default.
absolute
title.absolute can be used to provide a title that ignores title.template set in parent segments.
Good to know:
layout.jstitle(string) andtitle.defaultdefine the default title for child segments (that do not define their owntitle). It will augmenttitle.templatefrom the closest parent segment if it exists.title.absolutedefines the default title for child segments. It ignorestitle.templatefrom parent segments.title.templatedefines a new title template for child segments.
page.js- If a page does not define its own title the closest parents resolved title will be used.
title(string) defines the routes title. It will augmenttitle.templatefrom the closest parent segment if it exists.title.absolutedefines the route title. It ignorestitle.templatefrom parent segments.title.templatehas no effect inpage.jsbecause a page is always the terminating segment of a route.
description
Other fields
metadataBase
metadataBase is a convenience option to set a base URL prefix for metadata fields that require a fully qualified URL.
metadataBaseallows URL-basedmetadatafields defined in the current route segment and below to use a relative path instead of an otherwise required absolute URL.- The field's relative path will be composed with
metadataBaseto form a fully qualified URL.
Good to know:
metadataBaseis typically set in rootapp/layout.jsto apply to URL-basedmetadatafields across all routes.- All URL-based
metadatafields that require absolute URLs can be configured with ametadataBaseoption. metadataBasecan contain a subdomain e.g.https://app.acme.comor base path e.g.https://acme.com/start/from/here- If a
metadatafield provides an absolute URL,metadataBasewill be ignored. - Using a relative path in a URL-based
metadatafield without configuring ametadataBasewill cause a build error. - Next.js will normalize duplicate slashes between
metadataBase(e.g.https://acme.com/) and a relative field (e.g./path) to a single slash (e.g.https://acme.com/path)
URL Composition
URL composition favors developer intent over default directory traversal semantics.
- Trailing slashes between
metadataBaseandmetadatafields are normalized. - An "absolute" path in a
metadatafield (that typically would replace the whole URL path) is treated as a "relative" path (starting from the end ofmetadataBase).
For example, given the following metadataBase:
Any metadata fields that inherit the above metadataBase and set their own value will be resolved as follows:
metadata field | Resolved 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
Good to know:
- It may be more convenient to use the file-based Metadata API for Open Graph images. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you.
robots
icons
Good to know: We recommend using the file-based Metadata API for icons where possible. Rather than having to sync the config export with actual files, the file-based API will automatically generate the correct metadata for you.
Good to know: The msapplication-* meta tags are no longer supported in Chromium builds of Microsoft Edge, and thus no longer needed.
themeColor
Deprecated: The themeColor option in metadata is deprecated as of Next.js 14. Please use the viewport configuration instead.
colorScheme
Deprecated: The colorScheme option in metadata is deprecated as of Next.js 14. Please use the viewport configuration instead.
manifest
A web application manifest, as defined in the Web Application Manifest specification.
twitter
The Twitter specification is (surprisingly) used for more than just X (formerly known as Twitter).
Learn more about the Twitter Card markup reference.
viewport
Deprecated: The viewport option in metadata is deprecated as of Next.js 14. Please use the viewport configuration instead.
verification
appleWebApp
alternates
appLinks
archives
Describes a collection of records, documents, or other materials of historical interest (source).
assets
bookmarks
category
facebook
You can connect a Facebook app or Facebook account to your webpage for certain Facebook Social Plugins Facebook Documentation
Good to know: You can specify either appId or admins, but not both.
If you want to generate multiple fb:admins meta tags you can use array value.
pinterest
You can enable or disable Pinterest Rich Pins on your webpage.
other
All metadata options should be covered using the built-in support. However, there may be custom metadata tags specific to your site, or brand new metadata tags just released. You can use the other option to render any custom metadata tag.
If you want to generate multiple same key meta tags you can use array value.
Types
You can add type safety to your metadata by using the Metadata type. If you are using the built-in TypeScript plugin in your IDE, you do not need to manually add the type, but you can still explicitly add it if you want.
metadata object
generateMetadata function
Regular function
Async function
With segment props
With parent metadata
JavaScript Projects
For JavaScript projects, you can use JSDoc to add type safety.
Unsupported Metadata
The following metadata types do not currently have built-in support. However, they can still be rendered in the layout or page itself.
| Metadata | Recommendation |
|---|---|
<meta http-equiv="..."> | Use appropriate HTTP Headers via redirect(), Proxy, Security Headers |
<base> | Render the tag in the layout or page itself. |
<noscript> | Render the tag in the layout or page itself. |
<style> | Learn more about styling in Next.js. |
<script> | Learn more about using scripts. |
<link rel="stylesheet" /> | import stylesheets directly in the layout or page itself. |
<link rel="preload /> | Use ReactDOM preload method |
<link rel="preconnect" /> | Use ReactDOM preconnect method |
<link rel="dns-prefetch" /> | Use ReactDOM prefetchDNS method |
Resource hints
The <link> element has a number of rel keywords that can be used to hint to the browser that an external resource is likely to be needed. The browser uses this information to apply preloading optimizations depending on the keyword.
While the Metadata API doesn't directly support these hints, you can use new ReactDOM methods to safely insert them into the <head> of the document.
<link rel="preload">
Start loading a resource early in the page rendering (browser) lifecycle. MDN Docs.
<link rel="preconnect">
Preemptively initiate a connection to an origin. MDN Docs.
<link rel="dns-prefetch">
Attempt to resolve a domain name before resources get requested. MDN Docs.
Good to know:
- These methods are currently only supported in Client Components, which are still Server Side Rendered on initial page load.
- Next.js in-built features such as
next/font,next/imageandnext/scriptautomatically handle relevant resource hints.
Behavior
Default Fields
There are two default meta tags that are always added even if a route doesn't define metadata:
- The meta charset tag sets the character encoding for the website.
- The meta viewport tag sets the viewport width and scale for the website to adjust for different devices.
Good to know: You can overwrite the default viewport meta tag.
Streaming metadata
Streaming metadata allows Next.js to render and send the initial UI to the browser, without waiting for generateMetadata to complete.
When generateMetadata resolves, the resulting metadata tags are appended to the <body> tag. We have verified that metadata is interpreted correctly by bots that execute JavaScript and inspect the full DOM (e.g. Googlebot).
For HTML-limited bots that can’t execute JavaScript (e.g. facebookexternalhit), metadata continues to block page rendering. The resulting metadata will be available in the <head> tag.
Next.js automatically detects HTML-limited bots by looking at the User Agent header. You can use the htmlLimitedBots option in your Next.js config file to override the default User Agent list.
To fully disable streaming metadata:
Streaming metadata improves perceived performance by reducing TTFB and can help lowering LCP time.
Overriding htmlLimitedBots could lead to longer response times. Streaming metadata is an advanced feature, and the default should be sufficient for most cases.
Ordering
Metadata is evaluated in order, starting from the root segment down to the segment closest to the final page.js segment. For example:
app/layout.tsx(Root Layout)app/blog/layout.tsx(Nested Blog Layout)app/blog/[slug]/page.tsx(Blog Page)
Merging
Following the evaluation order, Metadata objects exported from multiple segments in the same route are shallowly merged together to form the final metadata output of a route. Duplicate keys are replaced based on their ordering.
This means metadata with nested fields such as openGraph and robots that are defined in an earlier segment are overwritten by the last segment to define them.
Overwriting fields
In the example above:
titlefromapp/layout.jsis replaced bytitleinapp/blog/page.js.- All
openGraphfields fromapp/layout.jsare replaced inapp/blog/page.jsbecauseapp/blog/page.jssetsopenGraphmetadata. Note the absence ofopenGraph.description.
If you'd like to share some nested fields between segments while overwriting others, you can pull them out into a separate variable:
In the example above, the OG image is shared between app/layout.js and app/about/page.js while the titles are different.
Inheriting fields
Notes
titlefromapp/layout.jsis replaced bytitleinapp/about/page.js.- All
openGraphfields fromapp/layout.jsare inherited inapp/about/page.jsbecauseapp/about/page.jsdoesn't setopenGraphmetadata.
Version History
| Version | Changes |
|---|---|
v15.2.0 | Introduced streaming support to generateMetadata. |
v13.2.0 | viewport, themeColor, and colorScheme deprecated in favor of the viewport configuration. |
v13.2.0 | metadata and generateMetadata introduced. |