Reputation: 2572
I'm loading a blog post from the server where I will have access to things like the blog post title. But according to the migration guide for app router this exists outside of my page. How do I update it?
async function onLoad (slug: string): Promise<PostInterface> {
const res = await API.get(`/posts?slug=${slug}`, {
headers: {
// ...
}
})
const post = res.data.data.posts[0]
if (!post) redirect('/404')
return post
}
export const metadata: Metadata = {
title: 'My Page Title That Needs To Be Replaced'
}
async function Page ({ params }: { params: { slug: string } }) {
const post = await onLoad(params.slug)
const { title } = post
// ... how do i change my document.title from server side?
// metadata.title = title will not work
}
export default Page
Upvotes: 1
Views: 240
Reputation: 310
You should export the generateMetadata from the page.tsx
import type { Metadata } from "next";
export const generateMetadata = async ({ params }: { params: { slug: string }}): Promise<Metadata> => {
// Your network call
const title = await fetch(`...`);
return {
title: `${title}`
}
}
You can see the generateMetadata
docs here.
Note: Fetch is cached across Pages and generateMetadata calls, so you will not be requesting twice.
fetch requests are automatically memoized for the same data across generateMetadata, generateStaticParams, Layouts, Pages, and Server Components. React cache can be used if fetch is unavailable.
Upvotes: 2