Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Markdown and MDX Sites

SEO in Gatsby: Head API, Sitemap and RSS

Add titles, meta tags and structured data with the Gatsby Head API, then generate sitemaps, RSS feeds and robots.txt so search engines and readers find you.

Pre-rendering is Gatsby's gift to search engines: every page is real HTML, so crawlers see your content without running JavaScript. What remains is the metadata around that content: a unique title and description per page, canonical URLs, social-sharing tags, a sitemap and a feed. This lesson covers each.

The Head API

Since Gatsby 4.19, every page or template can export a function named Head. Whatever it returns is placed in the document <head>. It replaces the older react-helmet approach and works in both pages and templates.

JSX
// src/templates/blog-post.js (real Gatsby, read-only)
export const Head = ({ data, location }) => {
  const post = data.markdownRemark
  const url = `https://example.com${location.pathname}`
  return (
    <>
      <title>{post.frontmatter.title} | My Blog</title>
      <meta name="description" content={post.frontmatter.description} />
      <link rel="canonical" href={url} />
      <meta property="og:type" content="article" />
      <meta property="og:title" content={post.frontmatter.title} />
      <meta property="og:url" content={url} />
      <meta name="twitter:card" content="summary_large_image" />
    </>
  )
}

Head receives location, params, data (the page query result) and pageContext. Only certain tags are allowed: title, meta, link, style, script, base and noscript. It is rendered on the server and not hydrated, so it cannot use state or effects.

A reusable SEO component keeps defaults in one place:

JSX
// src/components/seo.js (real Gatsby, read-only)
import * as React from "react"
import { useSiteMetadata } from "../hooks/use-site-metadata"

export function SEO({ title, description, pathname, children }) {
  const site = useSiteMetadata()
  const seo = {
    title: title ? `${title} | ${site.title}` : site.title,
    description: description || site.description,
    url: `${site.siteUrl}${pathname || ""}`,
  }
  return (
    <>
      <title>{seo.title}</title>
      <meta name="description" content={seo.description} />
      <link rel="canonical" href={seo.url} />
      {children}
    </>
  )
}
// In a page: export const Head = () => <SEO title="About" pathname="/about/" />

Titles and descriptions that work

  • Titles: unique per page, around 50-60 characters, the main topic first.
  • Descriptions: 120-160 characters, a summary written for humans.
  • One h1 per page, which usually repeats the title in other words.
  • Canonical URLs always use siteUrl from siteMetadata, so duplicates (for example with query strings) point to one address.
JS Stand-in: build and check head tags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Structured data

JSON-LD helps search engines understand articles. Add it as a script tag in Head:

JSX
// real Gatsby, read-only
<script type="application/ld+json">
  {JSON.stringify({
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: post.frontmatter.title,
    datePublished: post.frontmatter.date,
  })}
</script>

Sitemap

gatsby-plugin-sitemap writes sitemap-index.xml (and sitemap-0.xml) at build time. It requires siteUrl in siteMetadata, and it only runs in production builds.

JavaScript
// gatsby-config.js (real Gatsby, read-only)
plugins: [
  {
    resolve: "gatsby-plugin-sitemap",
    options: { excludes: ["/admin/*", "/404/"] },
  },
]

Submit the sitemap URL in Google Search Console and reference it from robots.txt. gatsby-plugin-robots-txt generates that file; alternatively, put a static robots.txt in the static folder, which is copied as-is to the site root.

RSS feed

gatsby-plugin-feed creates an XML feed from a query you provide. Readers and aggregators use it.

JavaScript
// gatsby-config.js (real Gatsby, read-only)
{
  resolve: "gatsby-plugin-feed",
  options: {
    feeds: [{
      output: "/rss.xml",
      title: "My Blog RSS",
      query: `{ allMarkdownRemark(sort: {frontmatter: {date: DESC}}, limit: 20) { nodes { excerpt html fields { slug } frontmatter { title date } } } }`,
      serialize: ({ query: { site, allMarkdownRemark } }) =>
        allMarkdownRemark.nodes.map((node) => ({
          title: node.frontmatter.title,
          date: node.frontmatter.date,
          description: node.excerpt,
          url: site.siteMetadata.siteUrl + node.fields.slug,
          guid: site.siteMetadata.siteUrl + node.fields.slug,
          custom_elements: [{ "content:encoded": node.html }],
        })),
    }],
  },
}

Add <link rel="alternate" type="application/rss+xml" href="/rss.xml" /> in the Head of your layout pages so feed readers can find it.

What the generators do (stand-in)

Both outputs are plain XML. This stand-in builds a sitemap and an RSS item list from a post array, escaping text properly.

JS Stand-in: sitemap and RSS XML

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Missing siteUrl: the sitemap plugin fails and canonical URLs are wrong.
  • Running the Head API with hooks other than useStaticQuery (it is server-only).
  • Duplicate titles across pages.
  • Putting noindex on staging but forgetting to remove it for production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the output of the exported Head function go?

    Gatsby places the returned elements in the HTML head of that page.
  2. 2. Which plugin generates sitemap-index.xml?

    gatsby-plugin-sitemap writes the sitemap files in production builds.
  3. 3. Why set a canonical link?

    Canonical URLs consolidate duplicate addresses into one.
  4. 4. Which tag types may the Head API contain?

    Only document-head elements are allowed.

Summary

  • Export Head from pages and templates for titles, meta, canonical links and JSON-LD.
  • Centralize defaults in siteMetadata and a shared SEO component.
  • gatsby-plugin-sitemap and gatsby-plugin-feed generate XML at build time; add robots.txt.
  • Keep titles unique and descriptions 120-160 characters.

Next: SSG, DSG and SSR rendering modes