A sitemap is a file that provides search engines with information about the pages, content, and structure of a website. It is usually in XML format and provides a list of URLs as well as other metadata about each URL, such as the last update date, change frequency, and priority. Sitemaps are specially designed to help search engines index and interpret a website's content more efficiently.
Importing Dependencies:
The script begins by importing the necessary modules:
The provided Node.js script generates a sitemap XML file for a Next.js website, enhancing search engine crawling and indexing. The script utilizes the 'fs' module to write the sitemap, 'globby' to find relevant page files, and 'prettier' to format the XML output.
import { writeFileSync } from 'fs';
import { globby } from 'globby';
import prettier from 'prettier';
Sitemap Generation Function:
The 'generate' function begins by resolving the Prettier configuration from 'prettierrc.js' to ensure consistent formatting. It then employs 'globby' to find relevant page files while excluding certain ones and proceeds to construct the sitemap XML using a template string.
async function generate() {
const prettierConfig = await prettier.resolveConfig('./.prettierrc.js');
const pages = await globby([
'pages/*.js',
'data/**/*.mdx',
'!data/*.mdx',
'!pages/_*.js',
'!pages/api',
'!pages/404.js',
]);
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${pages
.map((page) => {
const path = page
.replace('pages', '')
.replace('data', '')
.replace('.js', '')
.replace('.mdx', '');
const route = path === '/index' ? '' : path;
let date_ob = new Date();
return `
<url>
<loc>${`https://bytescrum.com${route}`}</loc>
<changefreq> daily </changefreq>
<priority> 0.8 </priority>
</url>
`;
})
.join('')}
</urlset>
`;
try {
const formatted = await prettier.format(sitemap, {
...prettierConfig,
parser: 'html',
});
writeFileSync('public/sitemap.xml', formatted);
console.log('Sitemap generated successfully.');
} catch (error) {
console.error('Error generating sitemap:', error);
}
}
generate();
Resolving Prettier Configuration: The script resolves the Prettier configuration from the project root's.prettierrc.js file. This setting ensures that the resulting sitemap XML is prepared according to the Prettier guidelines.
const prettierConfig = await prettier.resolveConfig('./.prettierrc.js');
Finding Relevant Page Files:
The globby function is used in the project to discover relevant page files. The globby function accepts an array of glob patterns and produces a list of file paths that match them. In this scenario, it searches for all JavaScript files in the pages directory and all Markdown files in the data directory, except for files beginning with _, the API directory, and the 404.js file.
const pages = await globby([
'pages/*.js',
'data/**/*.mdx',
'!data/*.mdx',
'!pages/_*.js',
'!pages/api',
'!pages/404.js',
]);
Generating the Sitemap XML:
The script generates the sitemap XML by utilizing a template string and iterating over the page's array to build the specific URL components for each page. It takes the path from each file, prepares the URL, sets the frequency of change to "daily," and gives each URL a priority of 0.8.
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${pages
.map((page) => {
const path = page
.replace('pages', '')
.replace('data', '')
.replace('.js', '')
.replace('.mdx', '');
const route = path === '/index' ? '' : path;
return `
<url>
<loc>${`https://bytescrum.com${route}`}</loc>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
`;
})
.join('')}
</urlset>
`;
Formatting the Sitemap XML:
The script then formats the resulting sitemap XML with Prettier. It uses the resolved Prettier settings and changes the parser to 'HTML' to ensure proper formatting.
const formatted = await prettier.format(sitemap, {
...prettierConfig,
parser: 'html',
});
Writing the Sitemap to File:
Finally, the script saves the structured sitemap to the project directory's public/sitemap.xml file.
writeFileSync('public/sitemap.xml', formatted);
Error Handling and Completion:
The script provides basic error handling to capture any issues that may arise during the sitemap-generating process.
try {
console.log('Sitemap generated successfully.');
} catch (error) {
console.error('Error generating sitemap:', error);
}
Add the following post-build script:
Add the 'postbuild 'script to your package.json file.
This script will be invoked automatically when the build script has been done. Substitute the path of your sitemap creation script for the placeholder.
"scripts": {
"build": "next build",
"postbuild": "node path/to/generate-sitemap.js"
}
When you run the npm run build command, your Next.js project will be built, and the 'postbuild' script will be executed, which will construct the sitemap and store it in the public directory.
Document tree of the website:
The final out of the code where the sitemap is executed successfully please go through the below-provided link for further information.
This script retrieves all pages from a Next.js project, creates an XML sitemap with particular URLs, and formats and saves the sitemap to a file using Prettier. The generated sitemap may be published to search engines, boosting the indexing and discoverability of the website.
Thank you for reading our blog. Our top priority is your success and satisfaction. We are ready to assist with any questions or additional help.
Warm regards,
ByteScrum Blog Team,