← All posts

Astro SEO: meta tags, canonical URLs and the sitemap

Astro SEO in code: one head component for titles and canonicals, a schema that requires them, a sitemap with real dates, and what to check.

QueryScope team · · 10 min read · astro seo developers

Astro SEO is mostly four things: a site URL in astro.config.mjs, one head component that prints the title, description and canonical for every page, a content collection schema that makes those fields required, and the @astrojs/sitemap integration. Astro prerenders every page to static HTML by default, so the tags you write are the tags Google reads. The parts that go wrong are quieter: a sitemap that dates every page to the last build, and two URLs for one page.

Below is the code for each step, a checklist to run before a launch, and the half most Astro guides stop short of: reading Search Console to pick the next page to change, and telling whether the change worked.

TL;DR:

  • Set site in astro.config.mjs. Astro uses it for canonical URLs and the sitemap.
  • Put <title>, the description and the canonical in one head component, and build the canonical with new URL(Astro.url.pathname, Astro.site).
  • Make title and description required in the collection schema, so a page without them fails the build.
  • Add @astrojs/sitemap, then give lastmod the date the content changed. The integration's own option stamps one date on every page.
  • After a launch, check the page in Search Console's URL Inspection, not only in your browser.

What does Astro already do for SEO?

Astro prerenders pages to static HTML unless you opt out, so titles, descriptions and body text are in the response without any JavaScript running. The output option defaults to 'static', which the docs describe as "Prerender all your pages by default". What Astro leaves to you is the content of the <head>, the sitemap and the URL shape.

That default matters more than any plugin. A crawler that reads only HTML sees the same page a browser does, which is not true of a site that fills in its head tags on the client. If you switch a route to on-demand rendering, the tags still come from the server, but two things in this guide change: the sitemap integration cannot list dynamic on-demand routes, and trailing-slash redirects start to apply.

How do you set meta tags in Astro?

Write one head component that takes a title and a description as props, prints them, and builds the canonical URL from the current path. Every layout uses that component, so no page can ship without the three tags. Astro's docs give the canonical line: new URL(Astro.url.pathname, Astro.site).

---
// src/components/BaseHead.astro
interface Props {
  title: string;
  description: string;
}

const { title, description } = Astro.props;
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

<title>{title}</title>
<meta name="description" content={description} />
<link rel="canonical" href={canonicalURL} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:url" content={canonicalURL} />

Astro.site comes from the site value in your config, and it is undefined when site is not set. Set it first:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  site: 'https://example.com',
});

The docs call site "Your final, deployed URL" and say Astro uses it "to generate your sitemap and canonical URLs in your final build". In development Astro.url is a localhost address, which is why the canonical is built from the path plus Astro.site and never from Astro.url on its own.

Where should each page's title and description live?

Keep them in the content's frontmatter and make them required in the collection schema. Astro validates every file against that schema, so a post without a description stops the build. That turns "we forgot the meta description" from something you find in Search Console weeks later into an error on your own machine.

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const blog = defineCollection({
  loader: glob({ base: './src/content/blog', pattern: '**/*.{md,mdx}' }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date().optional(),
  }),
});

export const collections = { blog };

The page that renders a post passes those fields straight into the head component:

---
// src/pages/blog/[id].astro
import { getCollection, render } from 'astro:content';
import BaseHead from '../../components/BaseHead.astro';

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({
    params: { id: post.id },
    props: { post },
  }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---

<html lang="en">
  <head>
    <BaseHead title={post.data.title} description={post.data.description} />
  </head>
  <body>
    <h1>{post.data.title}</h1>
    <Content />
  </body>
</html>

Two fields are worth adding once the basics work: a separate seoTitle for when the heading a reader sees should differ from the title in search results, and updatedDate, which the sitemap section below needs.

How do you add a sitemap in Astro?

Run npx astro add sitemap. With site set, the integration writes sitemap-index.xml and sitemap-0.xml into the build output, listing every prerendered page. Then point crawlers at the index from robots.txt. One limit from the docs: it "cannot generate sitemap entries for dynamic routes in SSR mode".

# public/robots.txt
User-agent: *
Allow: /
Sitemap: https://example.com/sitemap-index.xml

Pages are included by default. To leave some out, such as a thank-you page or a draft preview route, use the filter option, which receives each page's full URL and returns true or false:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';

export default defineConfig({
  site: 'https://example.com',
  integrations: [
    sitemap({
      filter: (page) => !page.includes('/thank-you'),
    }),
  ],
});

Skip changefreq and priority. Astro's own sitemap docs note that both "are ignored by Google".

Try it

Point an SEO agent at your own site, not just an essay about one.

QueryScope holds the plan for your site, reads your real Search Console, and hands the coding agent you already have one change at a time to rank for the searches you decided to win. From $49/month, everything included.

Why does the sitemap's lastmod need real dates?

Because Google only trusts lastmod while it matches reality. Its documentation says it uses the value "if it's consistently and verifiably" accurate. The integration's lastmod option applies one date to the whole site, and the docs' per-page example sets new Date(), so the easy paths both tell Google every page changed at once.

The per-page hook is serialize(), which runs on each entry before it is written. The integration does not know your content dates, so you hand it a lookup keyed by path:

// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
import { lastModified } from './src/last-modified.mjs';

export default defineConfig({
  site: 'https://example.com',
  integrations: [
    sitemap({
      serialize(item) {
        const path = new URL(item.url).pathname;
        const date = lastModified[path];
        if (date) {
          item.lastmod = new Date(date).toISOString();
        }
        return item;
      },
    }),
  ],
});
// src/last-modified.mjs
export const lastModified = {
  '/': '2026-11-01',
  '/pricing/': '2026-10-17',
  '/blog/astro-seo/': '2026-11-17',
};

Match the keys to the paths in your generated sitemap, trailing slash included. A hand-kept map is fine for a small client site. On a larger one, generate that file from the same updatedDate frontmatter the collection schema already validates. A page with no entry simply gets no lastmod, which is better than a wrong one.

Google's rule for when to move the date: it "should reflect the date and time of the last significant update to the page". A change to the main content counts. A new copyright year in the footer does not. How Google uses lastmod goes through the cases.

How do you keep one URL per page?

Pick one trailing-slash form and make the canonical, the internal links and the sitemap all use it. Astro's trailingSlash option defaults to 'ignore', which the docs describe as "Match URLs regardless of whether a trailing "/" exists". That is convenient in development and it means nothing in Astro stops both forms from being linked.

With the default build.format of 'directory', Astro writes each page as a folder with an index.html inside, so on a static host its natural URL ends in a slash. Setting trailingSlash: 'always' to match is the low-surprise choice:

// astro.config.mjs
export default defineConfig({
  site: 'https://example.com',
  trailingSlash: 'always',
});

For on-demand routes in production, the docs say a request for the other form is redirected, and that the redirect "will be a 301 (permanent) redirect" for GET requests. Prerendered pages are served by your host, so check there too: request the page with and without the slash and confirm one of them redirects to the other. If your host serves both with a 200, the canonical tag from the head component is what tells Google which one counts.

An Astro SEO checklist before launch

Run this against the built site, not the dev server, because Astro.url and redirects behave differently in development.

  • site is set to the production URL, with https://.
  • Every page has its own title and description. Search the build output for duplicate <title> values.
  • Every page has a canonical that uses the production domain and your chosen trailing-slash form.
  • The schema requires title and description, so a missing one fails the build.
  • sitemap-index.xml exists in the output, and robots.txt points at it.
  • lastmod values are content dates, and no two unrelated pages share today's date.
  • No noindex shipped by accident. Search the build output for it.
  • One URL per page: the non-canonical slash form redirects, or at least carries the right canonical.

What do you change next, and how do you know it worked?

Setup gets a page into Google. It does not tell you which page to work on, and that is the question a client asks a month after launch. The answer is in Search Console: which searches the site already shows for, where it sits on each, and which pages Google has not indexed.

Three checks cover most of it:

  1. URL Inspection, then "Test live URL". Read the title, description and canonical out of Google's copy of the page. Reading URL Inspection explains each field.
  2. Pages that are not indexed. A new page can wait weeks. Finding the pages Google has not indexed covers what each status means and which ones you can act on.
  3. One change at a time, with a date. Change a title, note the day, and wait for Google to recrawl before judging it. How to track an SEO change gives the wait for each kind of change.

An Astro site with its content in the repo suits this well, because every one of those changes is a commit. If you build Astro sites for clients, SEO for web agencies that build client sites in code shows how QueryScope does this per client: a plan read from the client's repo, one change at a time from your coding agent, and a dated record of each change. The same guide for the App Router is Next.js SEO.

Sources

  • Astro docs, @astrojs/sitemap (npx astro add sitemap; sitemap-index.xml and sitemap-0.xml; the robots.txt snippet; filter, serialize and the site-wide lastmod option; no entries for dynamic routes in SSR mode; changefreq and priority ignored by Google).
  • Astro docs, Configuration reference (site; trailingSlash and its 'ignore' default; the 301 redirect; output defaulting to 'static'; build.format defaulting to 'directory').
  • Astro docs, API reference (Astro.site, Astro.url, and the canonical URL example).
  • Astro docs, Content collections (src/content.config.ts; the glob loader and Zod schema; getCollection, render and getStaticPaths; schema violations reported as errors).
  • Google Search Central, Build and submit a sitemap (Google ignores priority and changefreq; lastmod used when consistently and verifiably accurate; what counts as a significant update).

Try it

Put an SEO agent in your editor.

Ask your coding agent what to work on. QueryScope reads your real Search Console, holds the searches you decided to win, and hands back one move at a time with the proof it worked. From $49/month, everything included. 1, 3 or 10 sites.