When building a website with Next.js 13, you'll likely need to display dynamic metadata like product names. There are two approaches for handling metadata in Next.js app directory: static and dynamic.
Static metadata looks like:
export const metadata: Metadata = {
title: '...',
description: '...',
}
However, dynamic metadata is more common for sites displaying changing content. After researching solutions, I realized the only way to show dynamic metadata was calling an API on each page. But fetching metadata from an API on every page felt inefficient.
That's when I discovered request memoization - deduplicating similar API requests to avoid wasting resources. Here's how it works:
This optimizations allows displaying dynamic SEO-friendly metadata in Next.js 13 without taxing our API. Request memoization is a simple but powerful strategy for improving performance in React and Next.js apps.
If you need a code reference, check it out below!
import Link from 'next/link';
import { Metadata, ResolvingMetadata } from 'next';
interface Params {
slug: string;
}
export async function generateMetadata({
params,
}: {
params: Params;
}): Promise<Metadata> {
const { slug } = params;
// read route params
const url = 'https://api.example.com/v1/component/' + slug;
// fetch data
const component_item = await fetch(url).then((res) => res.json());
console.log(component_item);
return {
title: component_item.name,
description: component_item.description,
};
}
Request Memoization
React extends the fetch API to automatically memoize requests that have the same URL and options. This means you can call a fetch function for the same data in multiple places in a React component tree while only executing it once.
For example, if you need to use the same data across a route (e.g. in a Layout, Page, and multiple components), you do not have to fetch data at the top of the tree then forward props between components. Instead, you can fetch data in the components that need it without worrying about the performance implications of making multiple requests across the network for the same data.
Resources for Dynamic Metadata
https://javascript.plainenglish.io/mastering-metadata-in-next-js-a-comprehensive-guide-to-seo-excellence-ab9c2cf0dc35
https://nextjs.org/docs/app/building-your-application/caching#request-memoization
https://www.slingacademy.com/article/next-js-how-to-set-page-title-and-meta-description/