New researchTechnical SEO & AI Search · 2027Explore the framework

Astro SEO: a step-by-step setup guide

Set up SEO in an Astro site from an empty project to a verified deploy: head tags, content collections, sitemap, hreflang, JSON-LD, redirects and build checks.

Part of the JavaScript SEO series. For the full picture, start with JavaScript SEO: the complete rendering and indexing guide.

Astro is a good starting point for SEO: it renders every page to HTML at build time, and its islands documentation says components ship as HTML and CSS with client-side JavaScript stripped unless you opt in with a client:* directive. Search engines get the full content in the first response, with no rendering queue in between.

What Astro doesn’t do is make SEO decisions. There is no SEO plugin writing your canonical tags or deciding which pages belong in the sitemap. This guide builds that layer step by step, from an empty project to a verified deploy, with code you can copy. For the reasoning behind each rule and the mistakes it prevents on any generator, read the static site SEO checklist alongside it. Building with React instead? The Next.js App Router guide covers the same setup.

The examples assume a static Astro site (no adapter) deployed to Vercel. Code follows the current Astro documentation, linked at each step. If you haven’t settled on Astro yet, the static site generator comparison weighs it against Next.js, Hugo, Eleventy and others.

Step 1: How should you configure astro.config for SEO?

Set three things before you write a page: the production URL, the URL format and the output format.

// astro.config.mjs
// @ts-check
import { defineConfig } from 'astro/config'

export default defineConfig({
  site: 'https://example.com',
  trailingSlash: 'always',
  build: { format: 'directory' }
})
  • site is your final, deployed URL. Astro’s configuration reference says it uses it to generate the sitemap and canonical URLs, and the API reference says Astro.site is undefined when it isn’t set. Without it, prerendered pages also get a localhost URL in Astro.url.
  • trailingSlash: 'always' matches build.format: 'directory', which writes /about/index.html for /about/. The configuration reference recommends this pairing (or 'never' with build.format: 'file') to keep dev and build consistent. The default is 'ignore'.
  • The reference also says trailing slashes on prerendered pages are handled by the host. You’ll set the same rule there in Step 9.

Pick the slash form now. Changing it after launch means redirecting every URL.

Step 2: Build one SEO component for the head

Every SEO tag comes from one component. Pages pass props to the layout; they never write <title>, canonical or robots tags themselves. Start with a small config file that both the component and the sitemap will read:

// src/seo-config.mjs
export const SITE_NAME = 'Example'

/** Pages kept out of search. The SEO component and the sitemap filter both read this list. */
export const NOINDEX_PATHS = ['/thank-you/', '/search/']
---
// src/components/SEO.astro
import { NOINDEX_PATHS } from '../seo-config.mjs'
import { alternatesFor } from '../i18n/translations.mjs'

interface Props {
  title: string
  description: string
  image?: string
  ogType?: 'website' | 'article'
  noindex?: boolean
}

const { title, description, image = '/og/default.png', ogType = 'website' } = Astro.props
const path = Astro.url.pathname
const noindex = Astro.props.noindex || NOINDEX_PATHS.includes(path)
const canonical = new URL(path, Astro.site)
const imageUrl = new URL(image, Astro.site)
const alternates = noindex ? null : alternatesFor(path)
---
<title>{title}</title>
<meta name="description" content={description} />
{noindex
  ? <meta name="robots" content="noindex" />
  : <link rel="canonical" href={canonical} />}

<meta property="og:type" content={ogType} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={imageUrl} />
{!noindex && <meta property="og:url" content={canonical} />}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content={imageUrl} />

{alternates && Object.entries(alternates).map(([lang, url]) => (
  <link rel="alternate" hreflang={lang} href={new URL(url, Astro.site)} />
))}
{alternates && <link rel="alternate" hreflang="x-default" href={new URL(alternates.en, Astro.site)} />}

Three decisions are built in:

  1. The canonical comes from the URL, never from a prop someone types. Google recommends a self-referencing canonical on the canonical page itself in its guide to consolidating duplicate URLs.
  2. A noindex page gets a robots meta instead of a canonical, and no og:url or hreflang. A page that says both “don’t index me” and “I’m the URL to index” sends mixed signals; the canonical errors guide covers the other conflicts to avoid.
  3. hreflang comes from one mapping (Step 6), so the head and the sitemap can’t disagree.

The layout wraps it:

---
// src/layouts/Base.astro
import SEO from '../components/SEO.astro'
const { lang = 'en', ...seo } = Astro.props
---
<!doctype html>
<html lang={lang}>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <SEO {...seo} />
    <link rel="alternate" type="application/rss+xml" title="Example blog" href={new URL('rss.xml', Astro.site)} />
    <slot name="head" />
  </head>
  <body>
    <slot />
  </body>
</html>

Keep the head slot for page-specific extras such as JSON-LD, never for robots or canonical tags. If a page adds <meta name="robots" content="noindex"> there, the SEO component still prints a canonical.

Titles and descriptions should be distinct per page. Google’s title link documentation says there’s no limit on <title> length, but titles are truncated to fit the device, and it warns against repeated or boilerplate titles.

Step 3: Set up content collections with SEO fields and one draft filter

Put the SEO fields in the collection schema so a missing description or an overlong title fails the build instead of shipping. The code follows Astro’s content collections guide:

// 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' }),
  schema: z.object({
    title: z.string(),
    seoTitle: z.string().max(60).optional(),
    description: z.string().min(50).max(160),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date().optional(),
    image: z.string().optional(),
    draft: z.boolean().default(false)
  })
})

export const collections = { blog }

The length limits are editorial choices, not Google rules. Pick yours and let the schema enforce them.

Then write one function that returns published posts, and use it everywhere: post pages, listings, the RSS feed, related posts. If each route calls getCollection with its own filter, one of them eventually forgets it and a draft goes live.

// src/lib/posts.ts
import { getCollection } from 'astro:content'

/** Published posts, newest first. Drafts appear only in `astro dev`. */
export async function getPublishedPosts() {
  const posts = await getCollection('blog', ({ data }) => (import.meta.env.PROD ? !data.draft : true))
  return posts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf())
}

The post route uses it in getStaticPaths, so a draft never gets a page in production:

---
// src/pages/blog/[...id].astro
import { render } from 'astro:content'
import Base from '../../layouts/Base.astro'
import JsonLd from '../../components/JsonLd.astro'
import { getPublishedPosts } from '../../lib/posts'

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

const { post } = Astro.props
const { Content } = await render(post)
const { title, seoTitle, description, image } = post.data
---
<Base title={seoTitle ?? title} description={description} image={image} ogType="article">
  <JsonLd slot="head" data={/* Step 4 */ {}} />
  <article>
    <h1>{title}</h1>
    <Content />
  </article>
</Base>

The page writes exactly one <h1>, from the post title. Markdown bodies start at ##.

Step 4: Add JSON-LD structured data per page type

Write structured data in templates, per page type, so every page of that type gets it. A tiny component handles the output:

---
// src/components/JsonLd.astro
const { data } = Astro.props
// Escape "<" so a value containing "</script>" can't end the tag early.
const json = JSON.stringify(data).replace(/</g, '\\u003c')
---
<script type="application/ld+json" set:html={json} />

For a blog post, build BlogPosting and BreadcrumbList in the post route:

const url = new URL(Astro.url.pathname, Astro.site).href
const data = [
  {
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    headline: title,
    description,
    datePublished: post.data.pubDate.toISOString(),
    dateModified: (post.data.updatedDate ?? post.data.pubDate).toISOString(),
    author: { '@type': 'Person', name: 'Jane Doe', url: new URL('/about/', Astro.site).href },
    image: [new URL(image ?? '/og/default.png', Astro.site).href],
    mainEntityOfPage: url
  },
  {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: [
      { '@type': 'ListItem', position: 1, name: 'Blog', item: new URL('/blog/', Astro.site).href },
      { '@type': 'ListItem', position: 2, name: title, item: url }
    ]
  }
]

Google’s Article structured data documentation lists no required properties and recommends author, datePublished, dateModified, headline and image. For author.name it asks for the name only, with url pointing to a page that identifies the author. Its structured data guidelines also require the markup to describe content visible on the page, so show the same dates and author in the post.

Listing pages need markup too, and they’re easy to forget because they have no front matter: a CollectionPage with an ItemList of the posts it shows works for the blog index and category pages. The structured data errors guide covers validation.

Step 5: How do you configure @astrojs/sitemap correctly?

Install the integration, then add the two things it can’t know: which pages are noindex and when each page really changed.

npx astro add sitemap

The sitemap integration documentation says it includes every page by default and writes sitemap-index.xml plus numbered files such as sitemap-0.xml. It doesn’t mention noindex, so a noindex page stays in the sitemap unless filter removes it. And it doesn’t read your content dates, so <lastmod> is yours to add through serialize.

// astro.config.mjs
// @ts-check
import { readdirSync, readFileSync } from 'node:fs'
import { defineConfig } from 'astro/config'
import sitemap from '@astrojs/sitemap'
import { NOINDEX_PATHS } from './src/seo-config.mjs'
import { alternatesFor } from './src/i18n/translations.mjs'

// path -> YYYY-MM-DD from each post's front matter (updatedDate, else pubDate).
const blogDir = './src/content/blog/'
const lastmod = new Map(
  readdirSync(blogDir)
    .filter((f) => f.endsWith('.md'))
    .map((f) => {
      const text = readFileSync(blogDir + f, 'utf8')
      /** @param {string} key */
      const field = (key) => text.match(new RegExp(`^${key}:\\s*["']?(\\d{4}-\\d{2}-\\d{2})`, 'm'))?.[1]
      return [`/blog/${f.replace(/\.md$/, '')}/`, field('updatedDate') ?? field('pubDate')]
    })
)

export default defineConfig({
  site: 'https://example.com',
  trailingSlash: 'always',
  build: { format: 'directory' },
  integrations: [
    sitemap({
      filter: (page) => !NOINDEX_PATHS.includes(new URL(page).pathname),
      serialize(item) {
        const path = new URL(item.url).pathname
        const date = lastmod.get(path)
        const group = alternatesFor(path)
        const links = group && [
          ...Object.entries(group).map(([lang, url]) => ({ lang, url: new URL(url, item.url).href })),
          { lang: 'x-default', url: new URL(group.en, item.url).href }
        ]
        return { ...item, ...(date ? { lastmod: date } : {}), ...(links ? { links } : {}) }
      }
    })
  ]
})

Why each piece:

  • filter reads the same NOINDEX_PATHS as the SEO component. One list decides both, so a page can’t be noindex and in the sitemap at once. Google’s sitemap guide says to list the URL you want shown in results, not every URL that leads to the same content.
  • lastmod comes from content dates, not the build. Google uses it only when it is consistently and verifiably accurate, for significant changes. Every build rewrites every file, so the file time means nothing. Pages without a content date (home, about) get no <lastmod> rather than an invented one. The sitemap lastmod guide covers what counts as significant.
  • No changefreq or priority. The integration docs and Google’s guide both say Google ignores them.

The config reads the Markdown files directly because astro:content isn’t available inside astro.config. The regex expects dates written as YYYY-MM-DD; if your posts live in subfolders, walk them too.

After building, open dist/sitemap-0.xml and confirm the 404 page and your noindex pages aren’t listed.

Step 6: How do you add hreflang to a multilingual Astro site?

Use Astro’s i18n routing for URLs, and a translation mapping of your own for hreflang. Astro’s internationalization guide covers locales, prefixes and fallbacks but doesn’t mention hreflang, so the tags are yours to add.

// astro.config.mjs (add to the config above)
i18n: {
  locales: ['en', 'es'],
  defaultLocale: 'en',
  routing: { prefixDefaultLocale: false }
}

With prefixDefaultLocale: false, English pages live at the root of src/pages/ and Spanish ones under src/pages/es/. Translated slugs can differ (/about/ and /es/sobre-nosotros/), so map them explicitly:

// src/i18n/translations.mjs
/** Each group lists one page in every language it exists in. Only add a language once the page is published. */
const GROUPS = [
  { en: '/', es: '/es/' },
  { en: '/about/', es: '/es/sobre-nosotros/' }
]

/** @param {string} path @returns {Record<string, string> | null} */
export function alternatesFor(path) {
  return GROUPS.find((group) => Object.values(group).includes(path)) ?? null
}

The SEO component (Step 2) and the sitemap serialize (Step 5) both read alternatesFor(), which satisfies the rules in Google’s localized versions guide:

  • Each version lists itself and every other version, because the whole group is printed on every page in it.
  • Links are reciprocal, because every page reads the same group.
  • x-default points to the English page as the fallback.
  • URLs are absolute, built with new URL(path, Astro.site).

Google treats HTML tags, HTTP headers and sitemaps as equivalent methods. Generating two of them from the same mapping keeps them identical; if you’d rather keep one, drop the links from serialize. The integration also has its own i18n option that derives alternates from URL prefixes, which works when translated pages share the same slug. The keys must be valid hreflang codes (en, es, pt-BR); if your locale folders use other names, map them.

Two rules the mapping can’t enforce by itself: don’t add a language to a group until that page is published, and never point a group at a noindex page. The hreflang errors guide covers the rest.

Astro’s i18n fallback can serve another language’s content at a missing locale’s URL (fallbackType: 'rewrite'). That creates a page in language A at a URL that claims language B. Leave missing translations out of the mapping, and link to the existing version instead.

Step 7: Add robots.txt, RSS and a real 404

robots.txt as an endpoint, so the sitemap URL follows site. The endpoints guide explains that src/pages/robots.txt.ts builds /robots.txt, and the API reference says site is available on the endpoint context:

// src/pages/robots.txt.ts
import type { APIRoute } from 'astro'

export const GET: APIRoute = ({ site }) => {
  const sitemap = new URL('sitemap-index.xml', site).href
  return new Response(`User-agent: *\nAllow: /\n\nSitemap: ${sitemap}\n`, {
    headers: { 'Content-Type': 'text/plain; charset=utf-8' }
  })
}

Google’s sitemap guide documents the Sitemap: line with an absolute URL. Don’t use robots.txt to keep pages out of search: Google’s noindex documentation says a page blocked by robots.txt can’t have its noindex read.

RSS with @astrojs/rss, fed by the same draft-free helper (the code follows Astro’s RSS recipe):

// src/pages/rss.xml.js
import rss from '@astrojs/rss'
import { getPublishedPosts } from '../lib/posts'

export async function GET(context) {
  const posts = await getPublishedPosts()
  return rss({
    title: 'Example blog',
    description: 'Guides from Example',
    site: context.site,
    items: posts.map((post) => ({
      title: post.data.title,
      description: post.data.description,
      pubDate: post.data.pubDate,
      link: `/blog/${post.id}/`
    }))
  })
}

404: create src/pages/404.astro with the layout and noindex. Astro’s pages documentation says it builds to 404.html and that most deploy services will find and use it. The host decides the status code, so test it after deploying (Step 10). Give the page links to your main sections. Never route unknown URLs to a page that answers 200; that is a soft 404.

Step 8: Images and fonts for Core Web Vitals

Use Astro’s built-in components rather than plain tags where you can.

Images. The images guide says <Image /> requires alt and infers width and height for local images to avoid layout shift. Images in public/ are never optimized, so keep content images in src/.

---
import { Image } from 'astro:assets'
import hero from '../assets/hero.png'
---
<Image src={hero} alt="Dashboard showing crawl results" priority />

The example output in the guide uses loading="lazy". For the largest image above the fold, add priority: the astro:assets reference says it sets eager loading, sync decoding and high fetch priority (added in Astro 5.10). A lazy-loaded hero image is a common cause of slow Largest Contentful Paint. Use alt="" only for decorative images.

Fonts. Astro’s Fonts API downloads and serves fonts from your site and generates fallbacks. Preload only what the first screen needs:

// astro.config.mjs
import { defineConfig, fontProviders } from 'astro/config'

export default defineConfig({
  fonts: [{ provider: fontProviders.fontsource(), name: 'Inter', cssVariable: '--font-body' }]
})
---
import { Font } from 'astro:assets'
---
<Font cssVariable="--font-body" preload />

The font loading guide covers how many files to preload and how to avoid shifts when the font swaps in. Social images are the other asset per page: give each page its own og:image, and if you render them at build time, check every language you publish for missing glyphs.

Step 9: How do you set up redirects and trailing slashes on Vercel?

Put them in vercel.json. A static Astro site doesn’t need the Vercel adapter: its documentation says you don’t need an adapter to deploy a static site.

Don’t rely on Astro’s redirects option here. The routing guide says that when building to HTML files the status code isn’t used, and the configuration reference says static builds without an adapter get a meta refresh page. Google interprets an instant meta refresh as a permanent redirect but recommends server-side redirects whenever possible.

{
  "$schema": "https://openapi.vercel.sh/vercel.json",
  "trailingSlash": true,
  "redirects": [
    {
      "source": "/:path*",
      "has": [{ "type": "host", "value": "example.vercel.app" }],
      "destination": "https://example.com/:path*",
      "permanent": true
    },
    { "source": "/index.html", "destination": "/", "permanent": true },
    { "source": "/:path+/index.html", "destination": "/:path+/", "permanent": true },
    { "source": "/sitemap.xml", "destination": "/sitemap-index.xml", "permanent": true },
    { "source": "/old-guide(/.*)?", "destination": "/blog/new-guide/", "permanent": true }
  ]
}

From Vercel’s vercel.json reference:

  • "trailingSlash": true redirects /about to /about/ with a 308 and leaves paths with a file extension alone, so /robots.txt and /rss.xml keep working. Left undefined, both forms answer without a redirect, which Vercel says could get both indexed.
  • "permanent": true sends a 308. Google’s HTTP status documentation treats 308 as equivalent to 301.
  • has with type: "host" limits a rule to one hostname, which is how the project’s .vercel.app domain is sent to your own.

On the default domain: Vercel’s guide to preview indexing says preview deployments get X-Robots-Tag: noindex automatically, but doesn’t say that for a production .vercel.app URL, hence the host redirect. Replace example.vercel.app with your project’s domain.

Write each redirect straight to its final URL, and test old paths with and without the trailing slash: a pattern like /old-guide/:path* may not match /old-guide/ itself, which is why the example uses (/.*)?. Rules that run one after another are the usual source of redirect chains.

Step 10: Check the build and the deploy

Static output can be checked before it ships. Add a postbuild script that reads dist/ and exits with an error when a rule is broken; npm runs it right after build, so a failure stops the deploy and the live site keeps its last version.

{
  "scripts": {
    "build": "astro build",
    "postbuild": "node scripts/check-seo.mjs"
  }
}

The static site SEO checklist linked above has a starter script that checks noindex pages against canonicals and the sitemap, and the <h1> count. Useful additions for the setup in this guide:

  • Every indexable page has a title and a description, and no two pages in the same language share one.
  • Every hreflang target is a built, indexable page.
  • Every internal link ends with / (except files) and points to a file in dist/.
  • Every <img> has alt, width and height.
  • Every JSON-LD block parses.

Some things exist only on the live site, because the host decides them. After each deploy that touches vercel.json:

curl -sI https://example.com/about | grep -iE "^(HTTP|location)"
curl -sI https://example.com/old-guide/ | grep -iE "^(HTTP|location)"
curl -s -o /dev/null -w "%{http_code}\n" https://example.com/no-such-page/

Expect a 308 to the slash URL, a 308 to the new guide, and a 404.

Then connect Google:

  1. Verify the domain in Search Console and submit https://example.com/sitemap-index.xml in the Sitemaps report. Google’s sitemap guide calls a sitemap a hint, so watch the report rather than assuming every URL is crawled.
  2. Inspect a few URLs per template with URL Inspection and compare the canonical Google selected with yours.
  3. Watch Page indexing for duplicates, soft 404s and “Crawled – currently not indexed”. The Search Console guide covers the reports.
  4. Crawl the live site regularly. A crawler such as Crawlens checks the deployed pages the way a search engine fetches them, including redirect chains, non-indexable URLs in sitemaps, hreflang without return links and invalid JSON-LD. Compare crawls before and after big changes.

Astro SEO setup checklist

  • site, trailingSlash and build.format set in astro.config.
  • One SEO component writes title, description, canonical or robots, Open Graph and hreflang.
  • Noindex pages listed once and read by both the SEO component and the sitemap filter.
  • Content schema enforces title and description; one helper filters drafts for every route.
  • One <h1> per page; distinct titles and descriptions.
  • JSON-LD per page type, posts and listings, matching visible content.
  • @astrojs/sitemap with filter and serialize; <lastmod> from content dates.
  • hreflang from one translation mapping, in the head and the sitemap.
  • robots.txt endpoint with the sitemap URL; RSS from the published posts; a noindex 404 page.
  • <Image /> with alt; priority on the hero image; fonts through the Fonts API.
  • vercel.json with trailingSlash, host and old-URL redirects; no meta refresh redirects.
  • Post-build checks fail the deploy; curl checks and Search Console after deploy; regular crawls.

Frequently asked questions

Is Astro good for SEO?

Astro renders pages to HTML on the server or at build time and ships no client JavaScript unless a component asks for it, so search engines get complete content in the first response. It doesn't write SEO tags for you; titles, canonicals, sitemaps and structured data are set up in your own code.

Does Astro add canonical tags automatically?

No. Astro gives you Astro.url and Astro.site, and you build the canonical from them in your layout. Set site in astro.config, or Astro.site is undefined and absolute URLs can't be built.

Does Astro i18n routing add hreflang tags?

Astro's internationalization guide covers locale routing and fallbacks but doesn't mention hreflang. Add the link tags yourself from a mapping of translated pages, and use the same mapping for sitemap alternates.

Should I use Astro's redirects option on a static site?

On a static build without an adapter, Astro writes redirects as HTML files with a meta refresh tag, not server redirects. For SEO, prefer real 301 or 308 redirects in your host's configuration, such as vercel.json.

Do I need the @astrojs/vercel adapter for a static Astro site?

No. The adapter's documentation says a static site doesn't need an adapter to deploy on Vercel. Use vercel.json for trailing slashes, redirects and headers.

· Founder, Crawlens

Dien builds Crawlens, a desktop crawler for technical SEO audits, and writes about the checks it runs: crawling, indexing, rendering and Search Console data.

Audit your own site with Crawlens

Crawl, run 70 checks, and see them next to Search Console and Core Web Vitals data.

Download free for Windows