Merge Layout and Page Metadata
Medium · Metadata
Layouts and pages can export a metadata object. For a page, Next.js starts with the layout's metadata and lets the page override it:
- The merge is **shallow**: every top-level field the page defines replaces the layout's field completely. If the page sets openGraph: { title: "Sale" }, the layout's siteName, images, ... are gone (a common surprise). Fields the page does not define are inherited.
- title can be a string or an object:
- title.template in a layout (like "%s | Acme") is applied to the titles of **child** segments. Replace every %s with the child title.
- title.default is the layout's own title, and the fallback for children that do not set a title. It is not templated.
- title.absolute ignores any template.
Write resolveMetadata(layout, page) that returns the page's merged metadata with title as a plain string:
- All fields except title: layout fields, then page fields on top.
- Layout title: a string, or the object's absolute / default. Its template (if any) is used for the page title.
- Page title missing: use the layout title.
- Page title string: apply the layout template (or use it as it is if there is none).
- Page title object: absolute if set; otherwise its default with the layout template. A page's own template would only affect its children, so ignore it.
- If neither sets a title, leave title out. Key order does not matter.
(Simplified to one layout and one page. Real Next.js does the same step by step for every nested layout, and also fills a few fields, like twitter from openGraph.)