0

I'm building a blog using Next.js and I'm utilizing the new app router for navigation. However, I'm encountering an issue where every blog page displays the same title and description. Upon investigating the code, I found that the title and description are exported as Metadata() from the layout.js file, which seems to be the main cause of the problem. When I tried to use Metadata() in individual blog pages, it didn't work as expected.

Is there a way I can resolve this issue and have different titles and descriptions for each blog page, even when using the app router and including a non-SSR page like Client? I would appreciate any guidance or suggestions on how to approach this problem.

morganney
  • 6,566
  • 1
  • 24
  • 35

3 Answers3

0

In Next.js 13, you can define static metadata by exporting a Metadata object from any layout.js or page.js file, but it's likely that you'll want to generate dynamic metadata for each page (metadata that depends on the fetched content for that page). To do dynamic metadata, you'll want to export a generateMetadata function

It's also possible that you'll find using a package like next-seo to be easier, although I didn't use it since Next.js 12 and don't know if it works with the new app directory.

0

In Next.js 13. You can use generateMetadata function to fetch metadata that requires dynamic values.

Official docs : https://nextjs.org/docs/app/building-your-application/optimizing/metadata

0

If your page title is static then you can create a new layout.js file to export the metadata with the new title.

.
├── app/
│   ├── client/
│   │   ├── layout.js // Create new title here
│   │   └── page.js // 'use client'
│   ├── layout.js
│   └── page.js
├── package.json
└── next.config.js

So in the above example, if client/page.js has a 'use client' directive you can change the page title by creating a sibling layout.js file that simply renders the children and updates the title:

client/layout.js

export const metadata = {
  title: 'New Title'
}
export default function ClientLayout({ children }) {
  return children
}

If the page title is based on dynamic content from an API then you can use the above approach for a default server-side implementation, and then update the document.title inside of a useEffect when client/page.js is rendered.

morganney
  • 6,566
  • 1
  • 24
  • 35