🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
SEO••By Komal Nakrani

Astro Meta Tags: Build a Reusable SEO Head Component

Build an Astro meta tags component: typed props for title, description, canonical, Open Graph, Twitter, noindex and hreflang, wired through one base layout.

#Astro#Meta Tags#SEO#Open Graph#Components

Astro meta tags belong in one component. Create src/components/SEO.astro with typed props for title, description, image and indexing, render it inside your base layout’s <head>, and pass page values down from each page. Every page then gets a unique title, description, canonical URL and social tags without repeating markup.

Astro doesn’t ship a built-in head manager, and it doesn’t need one. A component plus Astro.url and Astro.site covers everything a search engine or social preview reads.

Key Takeaways

  • Set site in astro.config.mjs first. Canonicals and Open Graph URLs must be absolute.
  • One SEO.astro component with a typed Props interface keeps every page consistent and catches missing values at build time.
  • Build canonical URLs from Astro.url.pathname and Astro.site, never from a hard-coded string.
  • Add noindex, article dates and hreflang alternates as optional props, so most pages pass only title and description.
  • Use a slot for one-off tags instead of growing the props list forever.

The tags every page needs

Before writing the component, settle on the list. These are the tags that search engines and social platforms actually read:

Tag Read by Notes
<title> Search results, browser tabs Unique per page, roughly 50 to 60 characters
<meta name="description"> Search snippets Unique per page, roughly 150 to 160 characters
<link rel="canonical"> Google, Bing Absolute URL of the preferred version
<meta name="robots"> Crawlers Only when you need noindex
og:title, og:description, og:image, og:url, og:type Facebook, LinkedIn, Slack, Discord, iMessage Image as absolute URL, ideally 1200 x 630
twitter:card X summary_large_image for a large preview
<link rel="alternate" hreflang> Google Only on multilingual sites

The keywords meta tag isn’t on the list. Google has ignored it for years.

Set site first

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

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

site turns Astro.site into a URL object, which the component uses to build absolute links. trailingSlash makes sure the canonical you generate matches the URL your host serves. The canonical URLs tip covers that mismatch in detail.

The Astro meta tags component

---
// src/components/SEO.astro
interface Props {
  title: string;
  description: string;
  image?: string;
  imageAlt?: string;
  type?: 'website' | 'article';
  noindex?: boolean;
  canonical?: string;
  publishedTime?: Date;
  modifiedTime?: Date;
}

const SITE_NAME = 'Example Studio';
const TWITTER_HANDLE = '@examplestudio';

const {
  title,
  description,
  image = '/og/default.jpg',
  imageAlt = SITE_NAME,
  type = 'website',
  noindex = false,
  canonical,
  publishedTime,
  modifiedTime,
} = Astro.props;

const canonicalURL = new URL(canonical ?? Astro.url.pathname, Astro.site);
const imageURL = new URL(image, Astro.site);
const fullTitle = title === SITE_NAME ? title : `${title} | ${SITE_NAME}`;
---
<title>{fullTitle}</title>
<meta name="description" content={description} />
<link rel="canonical" href={canonicalURL} />
{noindex && <meta name="robots" content="noindex, follow" />}

<meta property="og:site_name" content={SITE_NAME} />
<meta property="og:type" content={type} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:url" content={canonicalURL} />
<meta property="og:image" content={imageURL} />
<meta property="og:image:alt" content={imageAlt} />

{type === 'article' && publishedTime && (
  <meta property="article:published_time" content={publishedTime.toISOString()} />
)}
{type === 'article' && modifiedTime && (
  <meta property="article:modified_time" content={modifiedTime.toISOString()} />
)}

<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content={TWITTER_HANDLE} />

<slot />

A few decisions worth explaining:

  • Props interface. Astro type-checks props in .astro files. If a page forgets description, astro check and your editor flag it before deploy.
  • new URL(path, Astro.site). This produces an absolute URL from a relative path and also handles a full URL passed in (for an image on a CDN, say), because new URL() ignores the base when the first argument is already absolute.
  • Astro.url.pathname. This drops query strings like ?utm_source=... from the canonical, so tracking parameters don’t create duplicate URLs.
  • Title template. The home page passes the site name and gets it alone; every other page gets “Page | Site”. Put the template in one place and the whole site follows it.
  • <slot />. Pages that need one extra tag (a verification meta tag, a preload) pass it as a child instead of adding a prop used once.

Wire it into the base layout

---
// src/layouts/BaseLayout.astro
import SEO from '../components/SEO.astro';
import type { ComponentProps } from 'astro/types';

type Props = ComponentProps<typeof SEO>;
const props = Astro.props;
---
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
    <SEO {...props} />
  </head>
  <body>
    <slot />
  </body>
</html>

ComponentProps<typeof SEO> reuses the component’s prop types, so the layout and component can’t drift apart. Add layout-only props (like a hideNav flag) by extending that type.

Use it from pages

A static page:

---
// src/pages/about.astro
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout
  title="About us"
  description="A two-person studio building fast Astro sites for architects and interior designers since 2019."
>
  <h1>About us</h1>
</BaseLayout>

A blog post from a content collection:

---
// src/pages/blog/[id].astro
import { getCollection, render } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.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);
---
<BaseLayout
  title={post.data.title}
  description={post.data.description}
  image={post.data.image}
  type="article"
  publishedTime={post.data.pubDate}
  modifiedTime={post.data.updatedDate}
>
  <article>
    <h1>{post.data.title}</h1>
    <Content />
  </article>
</BaseLayout>

Because title and description are required in the collection schema, a post without them fails the build instead of shipping with empty tags.

Optional extras

noindex for utility pages

Thank-you pages, internal search results and paginated archives past page one are common noindex candidates:

<BaseLayout title="Thanks" description="Your message was sent." noindex>

noindex, follow keeps the page out of results but lets crawlers follow its links. Also exclude these pages from your sitemap, since listing a URL you’ve asked Google not to index sends mixed signals. The noindex tip shows the sitemap filter.

hreflang for translated pages

If the site uses Astro’s i18n routing, add alternates for each locale. Extend the props with a list of alternates and render them:

---
// inside src/components/SEO.astro, added to Props:
// alternates?: { lang: string; path: string }[];
const { alternates = [] } = Astro.props;
---
{alternates.map((alt) => (
  <link rel="alternate" hreflang={alt.lang} href={new URL(alt.path, Astro.site)} />
))}
{alternates.length > 0 && (
  <link rel="alternate" hreflang="x-default" href={new URL(alternates[0].path, Astro.site)} />
)}

Each language version must list all versions, including itself, or Google ignores the set.

Per-page Open Graph images

A generic share image works, but a per-post image with the title on it tells people what they’re clicking before they click. You can generate these at build time; the Astro Open Graph image guide shows how, and the image prop above accepts the generated path.

Structured data

JSON-LD is another head tag, but it’s large and page-type specific, so give it its own component rather than more props here. The Astro JSON-LD guide covers that component.

Checking the output

After npm run build, open a page in dist/ or view source on npm run preview:

npm run build
grep -o '<link rel="canonical"[^>]*>' dist/about/index.html

Then check social previews with each platform’s tools (LinkedIn’s Post Inspector, Facebook’s Sharing Debugger). Platforms cache previews, so re-scrape after changes.

Common mistakes these checks catch:

  1. Canonical pointing at localhost because site wasn’t set.
  2. og:image as a relative path, which most platforms reject.
  3. Duplicate <title> tags because a page also renders its own.
  4. A canonical without a trailing slash on a site that serves URLs with one.

Component or package?

Community packages such as astro-seo wrap the same tags behind a props object. They save a little typing and cover rarer tags. A hand-written component is about 60 lines, has no dependency to update, and does exactly what your site needs. For most sites, the component wins; reach for a package if you need dozens of rarely used tags.

The Astro SEO checklist puts this component in context with sitemaps, robots.txt and structured data. Every Komal theme is a complete Astro 7 project with its own layouts, so if you browse Astro themes you can study a finished base layout before you write your own. For where site and trailingSlash live, see the Astro config docs, and the official Astro.site reference explains the value it returns.

FAQ

How do I add meta tags to an Astro page?

Put them inside the <head> of a layout component and pass values as props from each page. Astro renders them as plain HTML at build time, so crawlers see them without running JavaScript. A shared SEO.astro component keeps them consistent.

How do I set a different title on each page in Astro?

Pass a title prop from the page to its layout, and render <title>{title}</title> in the layout’s head. For content collections, pass post.data.title from the dynamic route.

Why is my Astro canonical URL showing localhost?

site isn’t set in astro.config.mjs. Without it, Astro.site is undefined and URLs fall back to the dev server origin. Set site to your production URL and rebuild.

Do I need a package for SEO in Astro?

No. Astro renders head tags like any other HTML, so a component with typed props covers titles, descriptions, canonicals and social tags. Packages are optional convenience wrappers.

Where should Open Graph tags go in Astro?

In the same head component as the title and description, with absolute URLs for og:url and og:image. Build those URLs with new URL(path, Astro.site).