Optimization & SEO Best Practices
7 min read
Optimization & SEO Best Practices
Welcome back, developer! 🚀
You have built a website. It looks great on your localhost. But here is the hard truth: a beautiful website that nobody visits is like a billboard in the middle of the ocean. And a website that loads slowly is like a store where the door is stuck—people will leave before they even get in.
In this module, we are going to turn your Astro project into a high-performance race car that Google loves. We aren't just guessing here; we are using Astro’s built-in tools to handle the heavy lifting.
1. The Astro <Image /> Component: Perfect Web Vitals 🖼️
The Problem
Images are usually the heaviest things on a website.
In the "old days," you had to:
- Resize images in Photoshop.
- Save them as JPEGs, PNGs, and WebPs.
- Write complex HTML
<picture>tags to serve the right size to mobile vs. desktop. - Add "lazy loading" JavaScript so the browser doesn't crash.
If you uploaded a 5MB PNG directly to your <img> tag, your users on 4G networks would probably hate you.
The Solution: astro:assets
Astro has a built-in optimization pipeline. It does the math for you. It takes your high-quality image, automatically creates different sizes, converts them to modern formats (like WebP or AVIF), and lazy-loads them by default.
How to use it
First, where do your images live?
src/assets/: Put images here if you want Astro to optimize them. (Recommended)public/: Put images here if you want to skip optimization and serve them exactly as is (like a favicon).
Step 1: Import the component
Instead of the standard HTML <img>, we import <Image /> from astro:assets.
---
// src/pages/index.astro
import { Image } from 'astro:assets';
// Import the actual file. This allows Astro to know its original dimensions.
import myCoolImage from '../assets/robot-high-five.png';
---
<h1>Welcome to the future</h1>
<!-- The Magic Component -->
<Image
src={myCoolImage}
alt="A robot high-fiving a human"
width={600}
/>What just happened?
When you build this site, Astro will:
- Detect that
robot-high-five.pngis huge. - Convert it to
.webp(smaller file size, same quality). - Generate the HTML with
widthandheightattributes to prevent Cumulative Layout Shift (CLS). CLS is that annoying thing where text jumps around while images load. Google hates CLS.
Real-world Scenario: Density Pixel Ratios
Screens have different pixel densities (like Apple's Retina displays). A standard 1x image looks blurry on a modern phone.
The <Image /> component automatically generates a srcset. This tells the browser: "If the user has a 4k screen, download the big image. If they are on a cheap phone, download the tiny one."
Fact: Optimizing images is often the single most effective way to improve your Lighthouse Performance score.
2. Managing <head> Tags and Dynamic SEO Metadata
The Problem
Search engines (SEO) and Social Media bots (Open Graph) do not read your CSS. They read the <head> of your document.
If every page on your site just says <title>My Site</title>, Google thinks you have duplicate content, and Twitter/Discord won't show a cool preview card when you share a link.
The Solution: A Dynamic Layout
Instead of copy-pasting meta tags into every .astro file, we use a main Layout component that accepts "props" for the changing data.
Implementation
Create a reusable layout:
---
// src/layouts/MainLayout.astro
interface Props {
title: string;
description?: string;
image?: string;
}
const {
title,
description = "A default description for my awesome site.",
image = "/default-og-image.png"
} = Astro.props;
// Astro.url returns the current page URL (e.g., https://mysite.com/about)
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<!-- Dynamic Title -->
<title>{title}</title>
<!-- SEO Description -->
<meta name="description" content={description} />
<!-- Canonical URL: Tells Google "This is the original version of this page" -->
<link rel="canonical" href={canonicalURL} />
<!-- Open Graph (Facebook, Discord, LinkedIn) -->
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={new URL(image, Astro.url)} />
<meta property="og:url" content={Astro.url} />
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image" />
</head>
<body>
<slot />
</body>
</html>Now, use it in your pages:
---
// src/pages/about.astro
import MainLayout from '../layouts/MainLayout.astro';
---
<MainLayout
title="About Us | My Company"
description="Learn how we started our journey in 2024."
>
<h1>About Us</h1>
<p>We are cool.</p>
</MainLayout>Pro Tip: Always set a Canonical URL. Even if you don't copy your own content, URL parameters (like
?ref=twitter) can make Google think you have 50 versions of the same page. The canonical tag fixes this.
3. Generating Automated Sitemaps and RSS Feeds
The Problem: Sitemaps
A sitemap.xml is a map for robots. It lists every accessible URL on your site. Writing this manually is impossible once you have more than 5 pages.
The Solution: @astrojs/sitemap
Astro has an official integration that generates this automatically when you build your site.
Step 1: Install
Run this in your terminal:
npx astro add sitemapIt will automatically update your astro.config.mjs.
Step 2: Configure your site URL
For the sitemap to work, Astro needs to know your final domain name.
Open astro.config.mjs:
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
export default defineConfig({
site: 'https://www.your-production-domain.com', // <--- CRITICAL STEP
integrations: [sitemap()],
});When you run npm run build, a sitemap-index.xml and sitemap-0.xml will appear in your dist/ folder.
The Problem: RSS Feeds
RSS (Really Simple Syndication) allows users to subscribe to your blog without visiting it. It's an old standard, but still the gold standard for content distribution.
The Solution: The rss helper
Astro provides a helper package for this.
- Install:
npm install @astrojs/rss - Create the file:
src/pages/rss.xml.js(Yes, a.jsfile insidepages).
// src/pages/rss.xml.js
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
export async function GET(context) {
// Get all blog posts
const posts = await getCollection('blog');
return rss({
title: 'My Awesome Blog',
description: 'A humble developer learning Astro',
site: context.site, // Uses the 'site' from your astro.config
items: posts.map((post) => ({
title: post.data.title,
pubDate: post.data.pubDate,
description: post.data.description,
// Generate the link to the post
link: `/blog/${post.slug}/`,
})),
// Optional: add your custom XSL stylesheet for a pretty XML page
customData: `<language>en-us</language>`,
});
}Now, visiting localhost:4321/rss.xml generates a perfectly formatted feed.
4. Link Prefetching for Blazing Fast Navigation
The Problem
Astro is an MPA (Multi-Page Application) by default. When you click a link, the browser usually goes white for a split second, contacts the server, downloads the new HTML, and renders it.
Users perceive this as "slow" compared to SPAs (like React apps) that just swap content instantly.
The Solution: data-astro-prefetch
We can tell the browser: "Hey, the user is hovering over the 'Pricing' link. They are probably going to click it. Download the 'Pricing' page in the background NOW."
When the user actually clicks, the page is already in the cache. The navigation feels instant.
How to use it
In Astro, you simply add the data-astro-prefetch attribute to any <a> tag.
Basic Usage (Hover)
By default, this prefetches when the user hovers over the link.
<a href="/pricing" data-astro-prefetch>
Check our Pricing
</a>Advanced Strategies
You can change the strategy if you want to be more aggressive or conserve data.
tap: Prefetches only when the user starts clicking (touchstart/mousedown). Good for saving data.html<a href="/about" data-astro-prefetch="tap">About</a>viewport: Prefetches as soon as the link enters the screen. Very fast, but consumes more data.html<a href="/blog/next-post" data-astro-prefetch="viewport">Next Post</a>load: Prefetches as soon as the current page loads. Use sparingly (e.g., for the "Next Page" button in a wizard).html<a href="/step-2" data-astro-prefetch="load">Start</a>
Note: If you are using Astro's View Transitions (
<ViewTransitions />or the new Client Router), prefetching is usually enabled by default for all links. But if you are in standard MPA mode, this attribute is your best friend for perceived performance.
Summary Checklist 📝
- Images: Are you using
<Image />instead of<img>? - Head: Do you have a
title,description, andcanonicalURL on every page? - Discovery: Is
sitedefined in your config? Did you generate a sitemap? - Speed: Did you add
data-astro-prefetchto your main navigation links?
Now your Astro site isn't just code; it's a finely tuned machine ready for the production world. Go deploy! 🚀
References & Resources
Challenge
You are given an array of product objects. Each object contains a name, category, price, and quantity.
Your task is to implement a function named calculateCategoryTotals that accepts this array as its only argument.
Using the Array.prototype.reduce() method, transform the input array into a new object. This new object should have keys representing the unique product categories from the input array. The value for each key should be the total monetary value of all products belonging to that category, calculated by summing up the price * quantity for each product in that category.
Expected result
When the calculateCategoryTotals function is called with the provided products array, it should return an object with the total value for each category.
Correct Output:
{
"Electronics": 1325,
"Books": 180,
"Furniture": 150
}Calculation Details:
- Electronics:
(1200 * 1) + (25 * 2) + (75 * 1) = 1325 - Books:
(30 * 3) + (45 * 2) = 180 - Furniture:
(150 * 1) = 150