Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change title on page using a client component with app router in Next.js?

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.

like image 338
Jagdish Padeliya Avatar asked Dec 08 '25 01:12

Jagdish Padeliya


1 Answers

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.

like image 175
morganney Avatar answered Dec 11 '25 09:12

morganney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!