SEO with Next.js
In Chapter 8, we learned about SEO in full-stack apps. Next.js provides functionality for SEO out of the box. Let’s explore this functionality now, starting with adding dynamic titles and meta tags.
Adding dynamic titles and meta tags
In Next.js, we can statically define metadata by exporting a metadata object from a page.js
file, or we can dynamically define metadata by exporting a generateMetadata
function. We have already added static metadata to the root layout, as can be seen in src/app/layout.js
:
export const metadata = { title: 'Full-Stack Next.js Blog', description: 'A blog about React and Next.js', }
Now, let’s dynamically generate metadata for our post pages:
- Edit
src/app/posts/[id]/page.js
and define the following function outside of the page component:export async function generateMetadata({ params }) { const id = params.id
- Fetch the post; if it does not exist, call...