Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

SEO and sitemap

SEO is search engine optimization: clear titles, descriptions and addresses by which a search engine finds and shows your pages. Astro already serves ready HTML, which is good for search; what is left is filling in meta tags and making a sitemap, a file listing all pages.

The site address

Many features need the full site address. Set it in astro.config.mjs:

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

After that the address is available in components as Astro.site and in endpoints as context.site.

Meta tags in the layout

Add a description prop and tags to the <head> of the layout src/layouts/BaseLayout.astro:

---
interface Props {
  title: string;
  description?: string;
}
 
const { title, description = "Anna's blog about web development" } = Astro.props;
const canonical = new URL(Astro.url.pathname, Astro.site);
---
 
<head>
  <meta charset="utf-8" />
  <title>{title} | Anna's blog</title>
  <meta name="description" content={description} />
  <link rel="canonical" href={canonical} />
  <meta property="og:title" content={title} />
  <meta property="og:description" content={description} />
</head>

View the source of any page in the browser: <head> has the description and the full address https://blog.example.com/.... The canonical URL tells a search engine which address of the page is the main one. The og: tags are used by social networks and messengers for link previews.

A post description

On the post page, pass the description from the collection:

<BaseLayout title={post.data.title} description={post.data.description}>

Now each post has its own description in search results instead of one shared by the whole blog.

Sitemap

npx astro add sitemap

The command installs @astrojs/sitemap and adds sitemap() to integrations. The integration needs site from the config. Run npm run build and dist/ contains sitemap-index.xml and sitemap-0.xml with all pages. Add a link to the sitemap in <head>: <link rel="sitemap" href="/sitemap-index.xml" />.

robots.txt

The file for search robots goes into public/robots.txt:

User-agent: *
Allow: /
 
Sitemap: https://blog.example.com/sitemap-index.xml

It is copied to the site root and tells robots where the sitemap is.

Common mistake

People forget to set site in the config. Then Astro.site is undefined, the new URL() line for the canonical URL throws an error, and the sitemap integration creates no files and prints a warning. Set site first, before SEO and RSS.

Thanks for reading!

Donate to the site — we work hard for you.