Managing Metadata in Next.js
Now we are going to use metadata files to define metadata for our websites.
Favicon
Import your desired image inside app directory and rename it to favicon.ico. This should be enough to change the favicon of the webpage.
You can also define apple-icon.(jpg | jgeg | png) and icon.(jpg | jpeg | png | svg | ico) in the same way.
Opengraph-image and twitter-image
Add an opengraph-image.(jpg|jpeg|png|gif) and twitter-image.(jpg|jpeg|png|gif) image file to any route segment.
Add (opengraph-image | twitter-image).alt.txt to display text content when image can not be loaded.
robot.txt
It is a text file that provides instructions to web crawlers, on how to crawl and index a website.
Add robot.(js | ts) in app directory. Next.js will generate robot.txt from it.
import { MetadataRoute } from 'next'
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: '/',
disallow: '/admin/',
},
sitemap: 'https://aokura.site/sitemap.xml',
}
}
Sitemap
In Next.js sitemap.(xml | js | ts) is special file that is used to generate sitemap for the web application.
We can going to generate sitemap using sitmap.(js | ts).
import { MetadataRoute } from 'next'
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: `https://my-site.com/`,
lastModified: new Date(),
changeFrequency: 'daily',
priority: 1,
},
{
url: `https://my-site.com/updates`,
lastModified: new Date(),
changeFrequency: 'weekly',
priority: 0.6,
},
{
url: `https://my-site.com/achievements`,
lastModified: new Date(),
changeFrequency: 'monthly',
priority: 0.7,
}
]
}
We can view the generated sitemap in /sitemap.xml route.
We can use [Tex]generateSitemaps[/Tex] function for generating multiple sitemaps for the application. Let us see an example from Next.js docs
import { BASE_URL } from '@/app/lib/constants'
export async function generateSitemaps() {
/* Fetch the total number of products
and calculate the number of sitemaps needed
*/
return [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }]
}
export default async function sitemap({
id,
}: {
id: number
}): Promise<MetadataRoute.Sitemap> {
// Google's limit is 50,000 URLs per sitemap
const start = id * 50000
const end = start + 50000
const products = await getProducts(
`SELECT id, date FROM products WHERE id BETWEEN ${start} AND ${end}`
)
return products.map((product) => ({
url: `${BASE_URL}/product/${product.id}`,
lastModified: product.date,
}))
}
Static metadata
We can export metadata function from layout.tsx or page.tsx to set static metadata.
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'My website',
description: 'Metadata demo',
keywords: []
}
export default function Page() { }
Dynamic metadata
We can export special generateMetadata function which fetches dynamic metadata.
export async function generateMetadata(
{ params }: { params: { id: string } },
parent: ResolvingMetadata
): Promise<Metadata> {
const id = params.id;
const { data } = await axios.get < ProjectType > (`${server}/projects/${id}`);
const previousImages = (await parent).openGraph?.images || [];
return {
title: data.title,
keywords: [
data.category,
data.title,
],
openGraph: {
images: [data.image, ...previousImages],
},
};
}
Metadata Files Next.js
Metadata helps search engines index the content of a web page and helps users to find what they are looking for. Next.js 13 introduced new APIs which help developers to improve SEO in very simple ways. In this article, we are going to learn to define metadata in Next.js applications using meta files.
Table of Content
- What is Metadata?
- Why Metadata Matters?
- Different ways to add Metadata in Next.js 13
- Managing Metadata in Next.js
- Favicon
- Opengraph-image and twitter-image
- robot.txt
- Sitemap
- Static metadata
- Dynamic metadata
- Conclusion