Dynamic Sitemap (Recommended)
- Dynamic sitemaps are ideal for larger websites with dynamic content. You write code to generate the sitemap automatically based on your application data.
Steps to create Dynamic sitemap
- Install the next-sitemap package
npm install next-sitemap
- Create a file named sitemap.xml.js or sitemap.xml.ts (depending on your preference) in the app directory
- Import and use the sitemap function from next-sitemap
Example: This example shows the Dynamic sitemap.
import { Sitemap } from 'next-sitemap';
export default async function handler() {
try {
// Replace with logic to fetch or
// generate your website URLs dynamically
const urls = [];
const fs = require('fs');
// Replace with your directory path
const pagesDirectory = './pages';
if (fs.existsSync(pagesDirectory)) {
const files = fs.readdirSync(pagesDirectory);
for (const file of files) {
if (file !== 'sitemap.xml.js' && !file.startsWith('_'))
{ // Exclude this file and hidden files
// Extract slug from filename
const slug = file.replace(/\.jsx?$/, '');
urls.push({
loc: `https://your-website.com/${slug}`,
});
}
}
}
return Sitemap(urls).toXML();
} catch (error) {
console.error('Error generating sitemap:', error);
// Handle errors gracefully (e.g., return an empty sitemap or log the error)
// Return an empty sitemap to avoid server crashes
return Sitemap([]).toXML();
}
}
Output:
How to Create a Sitemap in Next.js 13?
The Sitemap is an XML file that notifies search engines like Google about the structure and content of the website. This would helps search engines to discover and index the pages efficiently which improve the website SEO (Search Engine Optimization).
Contact Us