How to Create Sitemap in Astro: Simple Guide
To create a sitemap in
Astro, use the official @astrojs/sitemap integration which automatically generates a sitemap.xml file based on your site pages. Install it via npm, add it to your astro.config.mjs, and build your project to get the sitemap ready.Syntax
The main syntax involves installing the @astrojs/sitemap package and adding it to your Astro config file.
npm install @astrojs/sitemap: Installs the sitemap integration.import sitemap from '@astrojs/sitemap';: Imports the integration inastro.config.mjs.integrations: [sitemap()]: Adds the sitemap integration to your Astro project.
This setup automatically scans your pages and generates a sitemap.xml file during build.
javascript
import { defineConfig } from 'astro/config'; import sitemap from '@astrojs/sitemap'; export default defineConfig({ site: 'https://example.com', integrations: [sitemap()], });
Example
This example shows a complete astro.config.mjs file with sitemap integration and the resulting sitemap.xml output after building.
javascript
import { defineConfig } from 'astro/config'; import sitemap from '@astrojs/sitemap'; export default defineConfig({ site: 'https://my-astro-site.com', integrations: [sitemap()], });
Output
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://my-astro-site.com/</loc>
</url>
<url>
<loc>https://my-astro-site.com/about/</loc>
</url>
<url>
<loc>https://my-astro-site.com/contact/</loc>
</url>
</urlset>
Common Pitfalls
Common mistakes when creating a sitemap in Astro include:
- Not setting the
siteproperty inastro.config.mjs, which is required for absolute URLs in the sitemap. - Forgetting to install the
@astrojs/sitemappackage before adding it to integrations. - Expecting sitemap updates without rebuilding the project.
Always rebuild your site after changes to ensure the sitemap is up to date.
javascript
/* Wrong: Missing site URL */ import { defineConfig } from 'astro/config'; import sitemap from '@astrojs/sitemap'; export default defineConfig({ integrations: [sitemap()], }); /* Right: Include site URL */ export default defineConfig({ site: 'https://example.com', integrations: [sitemap()], });
Quick Reference
Summary tips for creating a sitemap in Astro:
- Install
@astrojs/sitemapvia npm. - Set the
siteproperty inastro.config.mjsto your website URL. - Add
sitemap()to theintegrationsarray. - Run
npm run buildto generatesitemap.xml. - Deploy your site including the generated sitemap for SEO benefits.
Key Takeaways
Use the official @astrojs/sitemap integration for easy sitemap generation.
Always set the site URL in astro.config.mjs for correct sitemap links.
Rebuild your Astro project after adding or changing pages to update the sitemap.
The sitemap.xml file is generated automatically during the build process.
Check your sitemap output to ensure all pages are included correctly.