How to Add Sitemap to Next.js 14
Overview
Adding a sitemap to your Next.js 14 application is essential for SEO, ensuring that search engines can easily crawl and index your content. This guide walks you through the process of setting up a sitemap using the next-sitemap
package, including configuration, automation, and custom sitemaps.
To add a sitemap to a Next.js 14 application, you can generate a sitemap dynamically during the build process or at runtime. Here's how you can do it:
Install Dependencies
First, you need to install the next-sitemap
package, which is a popular solution for generating sitemaps in Next.js:
npm install next-sitemap --save-dev
Configure next-sitemap
Create a next-sitemap.config.js
file in the root of your project with the following configuration:
/** @type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: process.env.SITE_URL || 'https://yourdomain.com',
generateRobotsTxt: true,
changefreq: 'daily',
priority: 0.7,
sitemapSize: 7000,
};
Setting generateRobotsTxt
to true
, generates robots.txt
file along with the sitemap.
Exclude paths
If you want to skip few paths, you can add another attribute to the next-sitemap.config.js
file
/** @type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: process.env.SITE_URL || 'https://yourdomain.com',
generateRobotsTxt: true,
changefreq: 'daily',
priority: 0.7,
sitemapSize: 7000,
exclude: ["*/opengraph-image"],
};
Generate the Sitemap
You can now generate the sitemap using the following command:
npx next-sitemap
This will create a sitemap.xml
file (and a robots.txt
file if configured) in the public/
directory.
Automate Sitemap Generation (Optional)
To automate sitemap generation during the build process, you can add the npx next-sitemap
command to your package.json
scripts:
{
"scripts": {
"postbuild": "next-sitemap"
}
}
Now, every time you run npm run build
, the sitemap will be generated automatically.
Accessing the Sitemap
Once everything is set up, you can access your sitemap at https://yourdomain.com/sitemap.xml
.
Related Articles
Handling CORS Issues in Next.js 14 within Client Components
Different ways of handling CORS issue in Next.js 14 when making API calls from client components.
19/08/2024
Building A Reusable Generic Http Client In Nextjs 14
Learn how to build a reusable, type-safe HTTP client for making API requests with GET, POST, PUT, and DELETE methods.
04/10/2024
Recommended tsconfig settings For Nextjs 14
Recommended tsconfig settings for Nextjs 14
03/10/2024
How to Use CASL in Next.js for Role Based Access Control
How to use CASL in Next.js for role based access control
01/10/2024