#Metadata vs next/head

1 messages · Page 1 of 1 (latest)

hard wagon
#

Hi, I'm using nextjs app router. I have metadata setup on my layout.js file as you should for next app. But I wanted to update some head content like title, etc on a specific page by page basis. In previous nextjs version using the page router I'd use next/head on each page, but maybe there is a better method now for app router.

How can I do this?

upper cliffBOT
#

Hi @hard wagon. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, when using the App Router, you can define metadata for your application using the Metadata API. This can be done in two ways: Config-based Metadata and File-based Metadata.

Config-based Metadata allows you to export a static metadata object or a dynamic generateMetadata function in a layout.js or page.js file. Here's an example of how you can define static metadata:

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

Source (https://nextjs.org/docs/app/building-your-application/optimizing/metadata)

File-based Metadata involves adding static or dynamically generated special files to route segments. Once a file is defined, Next.js will automatically serve the file and update the relevant head elements with the correct metadata. Source (https://nextjs.org/docs/app/api-reference/file-conventions/metadata)

It's important to note that you should not manually add <head> tags such as <title> and <meta> to root layouts. Instead, you should use the Metadata API which automatically handles advanced requirements such as streaming and de-duplicating <head> elements. Source (https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#modifying-head)

#

If you want to update some head content like title, etc on a specific page by page basis, you can do so by defining the metadata in the specific page.js file. The metadata is evaluated in order, starting from the root segment down to the segment closest to the final page.js segment. 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. Source (https://nextjs.org/docs/app/building-your-application/optimizing/metadata#behavior)

So, if you define the title in your page.js file, it will override the title defined in your layout.js file.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: