Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Generate a dynamic sitemap.xml with Next.js

Tiempo de lectura: 2 minutos

Today we are going to learn how we can generate a sitemap.xml dynamically with Next.js. This is very useful if we have separate links for each of our articles and want to generate their sitemap.xml. With this technique, we will greatly improve the SEO of our website and help search engines properly index our site.

The first thing we’ll do is create a file called sitemap.xml.tsx.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const EXTERNAL_DATA_URL = 'https://jsonplaceholder.typicode.com/posts';
function generateSiteMap(posts) {
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<!--We manually set the two URLs we know already-->
<url>
<loc>https://jsonplaceholder.typicode.com</loc>
</url>
<url>
<loc>https://jsonplaceholder.typicode.com/guide</loc>
</url>
${posts
.map(({ id }) => {
return `
<url>
<loc>${`${EXTERNAL_DATA_URL}/${id}`}</loc>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
`;
})
.join('')}
</urlset>
`;
}
function SiteMap() {
// getServerSideProps will do the heavy lifting
}
export async function getServerSideProps({ res }) {
// We make an API call to gather the URLs for our site
const request = await fetch(EXTERNAL_DATA_URL);
const posts = await request.json();
// We generate the XML sitemap with the posts data
const sitemap = generateSiteMap(posts);
res.setHeader('Content-Type', 'text/xml');
// we send the XML to the browser
res.write(sitemap);
res.end();
return {
props: {},
};
}
export default SiteMap;
const EXTERNAL_DATA_URL = 'https://jsonplaceholder.typicode.com/posts'; function generateSiteMap(posts) { return `<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <!--We manually set the two URLs we know already--> <url> <loc>https://jsonplaceholder.typicode.com</loc> </url> <url> <loc>https://jsonplaceholder.typicode.com/guide</loc> </url> ${posts .map(({ id }) => { return ` <url> <loc>${`${EXTERNAL_DATA_URL}/${id}`}</loc> <changefreq>monthly</changefreq> <priority>0.5</priority> </url> `; }) .join('')} </urlset> `; } function SiteMap() { // getServerSideProps will do the heavy lifting } export async function getServerSideProps({ res }) { // We make an API call to gather the URLs for our site const request = await fetch(EXTERNAL_DATA_URL); const posts = await request.json(); // We generate the XML sitemap with the posts data const sitemap = generateSiteMap(posts); res.setHeader('Content-Type', 'text/xml'); // we send the XML to the browser res.write(sitemap); res.end(); return { props: {}, }; } export default SiteMap;
const EXTERNAL_DATA_URL = 'https://jsonplaceholder.typicode.com/posts';

function generateSiteMap(posts) {
  return `<?xml version="1.0" encoding="UTF-8"?>
   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <!--We manually set the two URLs we know already-->
     <url>
       <loc>https://jsonplaceholder.typicode.com</loc>
     </url>
     <url>
       <loc>https://jsonplaceholder.typicode.com/guide</loc>
     </url>
     ${posts
       .map(({ id }) => {
         return `
       <url>
           <loc>${`${EXTERNAL_DATA_URL}/${id}`}</loc>
           <changefreq>monthly</changefreq>
           <priority>0.5</priority>
       </url>
     `;
       })
       .join('')}
   </urlset>
 `;
}

function SiteMap() {
  // getServerSideProps will do the heavy lifting
}

export async function getServerSideProps({ res }) {
  // We make an API call to gather the URLs for our site
  const request = await fetch(EXTERNAL_DATA_URL);
  const posts = await request.json();

  // We generate the XML sitemap with the posts data
  const sitemap = generateSiteMap(posts);

  res.setHeader('Content-Type', 'text/xml');
  // we send the XML to the browser
  res.write(sitemap);
  res.end();

  return {
    props: {},
  };
}

export default SiteMap;

In this example, we are going to generate a sitemap.xml using sample data. You’ll need to create your own queries to iterate through each of your articles and generate their URL.

When we visit ourwebsite/sitemap.xml, it will display the pages added to the index.

Remember that the maximum URLs per sitemap.xml file are 50,000.

0

Leave a Comment