DEV Community

Cover image for Docusaurus: Copying the sitemap feature
Omar Hussein
Omar Hussein

Posted on

Docusaurus: Copying the sitemap feature

In my last post i talked about Docusaurus's sitemap generator feature that enhances the search engine optimization (SEO). By understanding its logic and flow, I successfully implemented a similar functionality tailored to my own application. I will do a quick walkthrough of my implementation, explaining the key decisions made during the process.

1. Understanding the Docusaurus Sitemap Generator Logic

Docusaurus's sitemap generator is designed to filter out specific routes based on exclusion criteria, ensuring that only SEO-friendly pages are included. Avoiding the exclusion criteria for now, I replicated this logic in my own implementation, focusing on two essential components:

a. Sitemap Construction:

To construct the sitemap, I utilized the popular npm package "sitemap." This package facilitates the creation of a structured sitemap, ensuring that each URL is correctly formatted with trailing slashes and base URLs. The use of the SitemapStream class enabled seamless construction and formatting of the sitemap content.

b. Integration and Usage:

I integrated my custom sitemap generator into my SSG application, similar to how it is seamlessly integrated into Docusaurus. This integration allows the sitemap generation process to be part of my build workflow, ensuring that an up-to-date sitemap is generated each time I update my website content.

2. Implementation Details

a. Initialization:

I initiated the sitemap generation process by initializing essential variables and validating the presence of the site's URL in the application configuration. This step ensures that the sitemap contains accurate and relevant URLs.

b. Sitemap Generation:

Valid routes, which passed the exclusion checks, were formatted with appropriate trailing slashes and base URLs. These formatted routes were added to the sitemap stream. Once all valid routes were added, the sitemap stream was converted into a string, representing the final structured sitemap content.

c. Getting the Routes:

One of the important steps was to get the route links dynamically. To achieve this, I designed a recursive mechanism that reads the output directory of my SSG application. By recursively traversing the directory structure, I gathered a map of all the files and their respective locations within folders. I then passed this information to the sitemap generator function which uses the paths as links.

The End

Understanding the inner workings of Docusaurus's sitemap generator gave me with valuable insights into creating SEO-friendly sitemaps for static websites and be able to generate the map dynamically based on the files rather than manually adjusting the map.

Top comments (0)