17 min readUpdated: November 24, 2026

22 Astro Best Practices: The Bookmark-Worthy Tips

A practical Astro 7.4 checklist for content sites: images, fonts, Tailwind, islands, content collections, Markdown, bundle analysis, Bun, i18n, SEO, and static deployment.

Available in:

At QuotyAI I use Astro for landing pages and this blog. It is a strong fit for content-first sites, provided you keep an eye on the JavaScript you add.

Built with the stack I’m writing about. This site runs Astro 7.4.x (^7.4.13), Vite 8, the default Sätteri Markdown pipeline, Tailwind v4 through Vite, TypeScript, MDX, and Mermaid. It builds to static files and deploys with Bun and Wrangler to Cloudflare Pages. Optional features such as the Fonts API or experimental build flags are recommendations, not a claim that every option is enabled here.

Version snapshot: 2026-11-24. This checklist targets Astro 7.4.x. The current installation guide requires Node.js 22.23.4 or higher; odd-numbered Node.js releases are not supported.

Astro does not make a slow site impossible. It gives you HTML-first defaults; images, fonts, third-party scripts, and island choices can still undo them.

My take: Astro’s real advantage is not “zero JavaScript by magic.” It is that every byte of client JavaScript becomes an explicit, reviewable decision.

Assets and Media

1. Use <Image /> for Local Images

Import images from src/ and let Astro process them at build time:

---
import { Image } from 'astro:assets';
import hero from '../assets/hero.png';
---
<Image src={hero} alt="Hero image" priority />

Astro infers dimensions to reduce layout shift and emits modern formats. Files in public/ and unauthorized remote images are not optimized. Use <Picture /> when you need multiple formats or art direction.

The priority prop is the intentional exception to lazy loading: it sets loading="eager", decoding="sync", and fetchpriority="high". Use it for the likely LCP image, not for every image above the fold. When a responsive layout is configured, Astro generates srcset and sizes; you usually do not need to specify widths manually.

Astro processes local images at build time and emits optimized files with dimensions

For projects that mix prerendered and on-demand pages, Astro 7.4 can use separate build and runtime image services. A local optimizer such as Sharp is often suitable at build time, while an image CDN may fit an edge runtime better.

My take: I treat image priority as a performance budget. One hero gets special treatment; everything else earns eager loading only with evidence.

See the image guide.

2. Use the Built-in Fonts API

Astro can download, cache, and self-host fonts, generate fallbacks, and add preload hints:

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

export default defineConfig({
  fonts: [{
    name: 'Inter',
    cssVariable: '--font-inter',
    provider: fontProviders.fontsource(),
    weights: ['400', '600', '700'],
    styles: ['normal'],
    subsets: ['latin', 'cyrillic', 'vietnamese'],
  }],
});
---
import { Font } from 'astro:assets';
---
<head>
  <Font
    cssVariable="--font-inter"
    preload={[{ weight: '400', style: 'normal', subset: 'latin' }]}
  />
</head>

Request only the weights, styles, and subsets your pages actually use. Astro 7.4 warns when a built-in provider cannot serve a configured value. If you maintain a custom provider, implement getFontProperties() now; it is optional in Astro 7 but will be required in Astro 8.

My take: Preloading an entire font family is not optimization. I preload the one file needed for the first screen and let the rest arrive when they are actually used.

See the Fonts API guide.

3. Use Tailwind v4 Through Vite and CSS Tokens

The current setup uses the Vite plugin, not the legacy Astro integration:

npx astro add tailwind
// astro.config.mjs
import { defineConfig } from 'astro/config';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
  vite: { plugins: [tailwindcss()] },
});
/* src/styles/global.css */
@import "tailwindcss";

@theme {
  --color-brand: oklch(0.75 0.18 175);
}

@theme inline {
  --font-sans: var(--font-inter);
}

Import the global stylesheet from a shared layout. When upgrading from Tailwind v3, remove @astrojs/tailwind from both dependencies and integrations. A JavaScript config is optional in v4; use it only for behavior that CSS cannot express.

Astro’s scoped <style> tags are often enough for component-specific CSS. Tailwind is a productive choice for utility-heavy layouts, but it is not an Astro requirement.

My take: I use utilities for layout and spacing, and CSS tokens for the visual identity. Mixing both is fine; duplicating the same design decisions in two systems is not.

See Astro’s styling guide.

Performance and Interactivity

4. Measure Client Bundles and Build Time

Do not optimize from intuition. Start with the official bundle-analysis recipe:

npm install rollup-plugin-visualizer --save-dev
// astro.config.mjs
import { defineConfig } from 'astro/config';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  vite: {
    plugins: [visualizer({ emitFile: true, filename: 'stats.html' })],
  },
});
astro build --timings

For a fully static site, stats.html appears at the root of dist/. With on-demand rendering, expect separate client and server reports under dist/client/ and dist/server/.

The visualizer shows dependencies used across the site; it does not show the exact bundle downloaded by each page. Use browser DevTools and real page measurements to confirm the user impact. Astro 7.4’s --timings report complements it by breaking down build phases, Vite plugins, Markdown, rendering, images, and integrations.

This repository also has a Brotli-based bun run perf:budget check for the landing page. A visual report explains what is heavy; a budget prevents it from quietly becoming heavy again. Keep diagnostic reports out of production deployments.

My take: I want a baseline before I touch an island, font, or dependency. “It feels faster” is not a measurement.

See the bundle-analysis recipe.

5. Start with .astro, Native HTML, and Small Scripts

Plain .astro components render to HTML and do not ship a UI-framework runtime. Framework components are also rendered to static HTML by default unless you add a client:* directive.

For a menu, disclosure, copy button, or small DOM enhancement, a processed Astro <script> is often enough:

<button type="button" data-copy>Copy</button>

<script>
  const buttons = document.querySelectorAll<HTMLButtonElement>('[data-copy]');

  buttons.forEach((button) => {
    button.addEventListener('click', async () => {
      const text = button.dataset.text;
      if (text) await navigator.clipboard.writeText(text);
      button.textContent = 'Copied';
    });
  });
</script>

Astro processes these scripts as TypeScript modules, bundles imports, deduplicates them per page, and may inline small scripts. Native elements such as <details>, <dialog>, and the Popover API can remove the need for JavaScript entirely. Starlight 0.42 used the Popover API so its mobile menu still works when JavaScript is disabled.

The Evil Martians case study shows the next step: they migrated existing React components unchanged, then reduced homepage JavaScript at load by 61% by hydrating smaller sections independently. Those numbers are specific to their site, but the method is reusable.

Static HTML surrounds independently hydrated interactive islands

My take: I do not add a framework island for behavior the browser already provides. Progressive enhancement is still one of the best performance features on the web.

6. Choose the Right client:* Directive

Directive Hydration timing Typical use
client:load Immediately Critical above-fold UI
client:idle When the browser is idle Non-critical widgets
client:visible When the component enters the viewport Below-fold UI
client:media="(max-width: 50em)" When a media query matches Mobile-only controls
client:only="react" Client only, no SSR output Browser-API-dependent UI

Use client:idle={{ timeout: 500 }} to bound the wait. Use client:visible={{ rootMargin: '200px' }} to start loading shortly before an island becomes visible, giving slow connections more time.

client:only requires the framework name and can display fallback content through a slot="fallback". All other client directives server-render the component first. Accessibility-related JavaScript must still be available when users need it; deferring a focus-management script can create a real usability problem.

Islands hydrate independently, and a framework runtime is shared once per page when multiple islands use it. Shared chunks can still be requested earlier than an individual island hydrates.

My take: client:visible is my default for below-fold interactivity. client:load has to justify itself.

See the directives reference.

7. Enable Prefetch Deliberately

// astro.config.mjs
export default defineConfig({
  prefetch: {
    prefetchAll: false,
    defaultStrategy: 'hover',
  },
});

Or opt in for a likely next step:

<a href="/blog/another-post/" data-astro-prefetch="viewport">Read more</a>

Astro supports hover, tap, viewport, and load strategies. It falls back to tap on slow connections or when data saver mode is enabled. Prefetch works for internal links and depends on appropriate cache headers, especially in Firefox and Safari.

One easy mistake is adding <ClientRouter /> without reviewing prefetch: it enables prefetchAll: true by default. Set prefetch: false or prefetchAll: false explicitly if you want link-level control.

The Evil Martians migration removed Gatsby behavior that prefetched 13.6 MB of query data for links visitors never clicked. Astro’s hover-based prefetch was intentionally less aggressive.

My take: Prefetch is a prediction about user intent. I enable it for the next article, pricing page, or documentation step—not for every link on the page.

See the prefetch guide.

8. Prefer Browser-Native View Transitions

Browser-native, cross-document view transitions can animate navigation without adding client-side routing JavaScript. If that covers your needs, prefer it.

Astro’s <ClientRouter /> adds SPA-like navigation, persistent elements, lifecycle events, and fallback animations:

---
import { ClientRouter } from 'astro:transitions';
---
<head>
  <ClientRouter />
</head>

That extra power has costs: bundled module scripts do not automatically re-run after navigation, state may need explicit persistence, and client-side routing changes how forms and links behave. Astro handles route announcements and disables animations for prefers-reduced-motion, but you still need to test the experience.

Astro’s CSP support still does not support <ClientRouter />. Astro 7.1 added finer-grained script and style CSP directives, but that does not remove this particular limitation.

My take: Animation is not worth an SPA-shaped maintenance burden. I start with native transitions and add <ClientRouter /> only when I need its routing features.

See View Transitions.

Content and Build Tooling

9. Define Typed Build-Time Collections

// 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,mdx}' }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date().optional(),
    draft: z.boolean().default(false),
    tags: z.array(z.string()),
  }),
});

export const collections = { blog };

Astro validates frontmatter and generates types. Schemas can also use image() to validate and import cover images and reference() to relate authors or posts.

Two details matter in production:

  • Collection order is non-deterministic. Sort explicitly by pubDate or another stable key.
  • Collections do not create index pages, RSS feeds, or draft filtering for you. Those remain application decisions.

Live collections belong in src/live.config.ts and use defineLiveCollection(). They require on-demand rendering, fetch per request unless cached, have no persistent data store, and do not support runtime MDX or image optimization. Prefer build-time collections for relatively static content.

Markdown and MDX files pass through loaders and Zod schemas into Astro's content layer

My take: A schema is executable editorial policy. It catches missing descriptions and malformed dates before they become production bugs.

See Content Collections.

10. Scale Content Builds Without Guessing

For large Markdown collections, Astro 7.1 can defer rendering until a page actually needs an entry:

loader: glob({
  base: './src/content/docs',
  pattern: '**/*.md',
  deferRender: true,
})

This lowers memory usage during content sync, at the cost of not caching rendered HTML across builds. It applies to Markdown, not MDX or data entries.

Astro 7.2 also introduced experimental incremental static builds:

// astro.config.mjs
export default defineConfig({
  experimental: { incrementalBuild: true },
});

A generated route opts in by returning a cacheKey. For collection entries, entry.digest is a convenient value because it changes when the content changes:

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  return posts.map((post) => ({
    params: { slug: post.id },
    props: { post },
    cacheKey: String(post.digest),
  }));
}

Astro hashes the route’s module graph as well, so changes to layouts, components, assets, or dependencies invalidate affected pages. Persist cacheDir between CI builds to benefit from the cache; astro build --force bypasses it.

The feature is still experimental. It is disabled when build.concurrency is greater than 1, and middleware changes do not invalidate cached pages. Astro 7.4’s experimental parallelPrerender can use multiple CPU cores, but each worker costs memory, pages do not share module-level variables, and some props cannot be serialized across workers.

My take: Run astro build --timings first. Experimental build flags are tools for a measured bottleneck, not a default performance ritual.

See the incremental-build reference.

11. Use MDX When Content Needs Components

npx astro add mdx

MDX lets an article import components, use expressions, and export data. It inherits your Markdown configuration by default, while allowing MDX-specific overrides.

Add a client:* directive to interactive framework components inside MDX. If you need recma plugins, use the Unified processor; the older MDX recmaPlugins option is deprecated.

Do not reach for MDX when a normal .md file or .astro page is enough. Every additional authoring feature is another thing contributors must understand.

My take: MDX is excellent for a custom diagram or interactive example. It is overkill for a paragraph that needs bold text.

See the MDX guide.

12. Use <Code /> for Dynamic Code Blocks

---
import { Code } from 'astro:components';
import snippet from '../examples/example.ts?raw';
---
<Code code={snippet} lang="ts" theme="github-dark" />

<Code /> uses Shiki and supports themes, languages, wrapping, and transformers. It does not inherit the Markdown shikiConfig; pass a theme when you need one.

Markdown code fences use Shiki by default with github-dark and produce inline styles without client-side JavaScript. If your project requires Astro’s CSP support, note that Shiki’s inline styles are not currently supported; Prism is the documented alternative.

See the Syntax Highlighting guide.

13. Know the Astro 7 Markdown and Compiler Defaults

Sätteri is the default .md and .mdx pipeline. It needs no installation unless you want to configure features or plugins. Install @astrojs/markdown-satteri for Sätteri-specific plugins.

If you still need remark, rehype, or recma plugins, install @astrojs/markdown-remark and opt into Unified:

import { defineConfig } from 'astro/config';
import { unified } from '@astrojs/markdown-remark';

export default defineConfig({
  markdown: { processor: unified() },
});

Both processors provide GitHub-Flavored Markdown and smart punctuation by default. Port plugins to Sätteri where practical instead of keeping the legacy pipeline forever.

Astro 7 also made the Rust compiler the only compiler. It is faster but stricter: unclosed tags can fail the build, and invalid HTML nesting is no longer silently repaired. The default compressHTML: 'jsx' mode can also remove whitespace between inline elements; write an explicit {' '} when that space matters.

My take: Stricter defaults are a gift when you read the error message. Fix the HTML instead of working around the compiler.

See the Astro 7 upgrade guide.

14. Use the Stable Logger API

Astro 7 moved logging out of the experimental block:

import { defineConfig, logHandlers } from 'astro/config';

export default defineConfig({
  logger: logHandlers.json({ level: 'warn' }),
});

Use Astro.logger.info(), .warn(), and .error() during rendering instead of ad hoc console output. Astro 7.2 accepts relative custom logger entrypoints, and Astro 7.3 passes the runtime logger into custom image services and cache providers so their warnings respect your configuration and --silent.

Avoid putting secrets or personal data into logs. A structured logger is still a place where sensitive data can leak.

See the Logger API.

15. Run astro check in CI

astro build transpiles TypeScript; it does not type-check it. Add an explicit check to your build pipeline:

{
  "scripts": {
    "check": "astro check",
    "build": "astro check && astro build"
  }
}

Use Astro’s strict or strictest TypeScript template, include .astro/types.d.ts, and exclude dist. The editor plugin improves the development experience, but it does not replace a command-line check.

My take: A type error caught in CI is cheaper than a runtime error caught by a reader.

See the TypeScript guide.

Internationalization

16. Plan i18n Routing Early

export default defineConfig({
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'ru', 'vi'],
    routing: { prefixDefaultLocale: false },
  },
});

Create locale folders under src/pages/ for routed pages, organize translated collection content consistently, and use helpers such as getRelativeLocaleUrl() from astro:i18n.

Astro.currentLocale is available even on static pages. Browser-preference APIs such as Astro.preferredLocale are for on-demand rendering. Configure fallbacks deliberately and choose between redirect and rewrite behavior.

Astro computes routes; it does not translate pages, generate hreflang, or build a language switcher for you. This site generates its alternate links explicitly.

My take: Decide whether the default language gets a URL prefix before you have hundreds of translated routes. Changing that policy later is a migration, not a config tweak.

See the i18n guide.

SEO and Discovery

17. Add a Sitemap and Localized Alternates

npx astro add sitemap
import sitemap from '@astrojs/sitemap';

export default defineConfig({
  site: 'https://example.com',
  integrations: [
    sitemap({
      i18n: {
        defaultLocale: 'en',
        locales: { en: 'en-US', ru: 'ru-RU', vi: 'vi-VN' },
      },
    }),
  ],
});

The integration generates sitemap-index.xml and numbered sitemap files from statically generated routes, including routes produced by getStaticPaths(). It cannot discover dynamic SSR routes. Use filter() and serialize() to remove private pages or customize entries.

This repository uses a custom /sitemap.xml because its locale and content-specific rules are easier to express in an endpoint. For a new site, I would start with the official integration and customize only where it falls short.

See the sitemap guide.

18. Always Set site

site enables absolute canonical URLs, sitemap generation, Astro.site, and reliable RSS links. Without it, URL-dependent features cannot know the production origin.

Use new URL('rss.xml', Astro.site) or endpoint context values instead of concatenating strings. It handles base paths and trailing slashes more safely.

19. Keep URL and Pagination Strategies Consistent

export default defineConfig({
  trailingSlash: 'always',
  build: { format: 'directory' },
});

Keep internal links, canonical tags, sitemap entries, and RSS links aligned. For prerendered pages, the host’s redirect behavior also matters; Astro cannot enforce every static-host rewrite.

If you build .html files with build.format: 'file', Astro 7.1 lets you adapt pagination URLs:

return paginate(posts, {
  pageSize: 10,
  format: (url) => `${url}.html`,
});

Astro 7.4 also adds an experimental custom redirect page for static builds. It can render localized redirect text through src/pages/3xx.astro, which is useful for multilingual migrations.

My take: Pick one canonical URL shape and make every generator obey it. SEO problems often begin as small URL inconsistencies.

20. Add RSS With Autodiscovery

Create a route such as src/pages/rss.xml.js using @astrojs/rss. Filter drafts, sort by pubDate, and use absolute links derived from the configured site:

const posts = (await getCollection('blog', ({ data }) => !data.draft))
  .sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());

return rss({
  title: 'Example Blog',
  description: 'New articles and notes',
  site: context.site,
  items: posts.map((post) => ({
    title: post.data.title,
    description: post.data.description,
    pubDate: post.data.pubDate,
    link: `/blog/${post.id}/`,
  })),
});

For a multilingual site, generate one feed per locale and filter by language. @astrojs/rss defaults to trailing slashes regardless of project configuration; set trailingSlash: false when your site uses trailingSlash: 'never'.

Add feed autodiscovery to the page head:

<link
  rel="alternate"
  type="application/rss+xml"
  title="Example Blog RSS"
  href={new URL('rss.xml', Astro.site)}
/>

Full-content RSS needs extra care: relative links and images must be made absolute, HTML should be sanitized, and MDX components are not rendered by a plain Markdown parser.

See the RSS recipe.

Deployment and Tooling

21. Deploy Static Output Without an Adapter

With output: 'static', deploy dist/ to a static host. A purely static site does not need an Astro adapter.

This repository currently uses Cloudflare Pages:

bun run build && wrangler pages deploy dist --branch=main

Cloudflare now recommends Workers for new projects. A static Worker can also serve dist/ through a minimal Wrangler assets configuration and wrangler deploy, still without the Astro Cloudflare adapter. The adapter is for on-demand rendering and currently targets Workers, not Pages.

Use npx astro add cloudflare when you need server rendering, server islands, actions, or sessions—not merely to publish static files.

My take: The important boundary is static versus on-demand, not Pages versus Workers. Choose the host from the runtime you actually need.

See the Cloudflare deployment guide.

22. Use Bun Deliberately

Astro officially supports Bun for project creation, dependency installation, integrations, development, builds, previews, and tests:

bun create astro my-astro-project-using-bun
bun install
bun add -d @types/bun
bun astro add react
bun run dev
bun run build
bun run preview
bun test

Bun can be a good fit when your team already uses it. Astro’s recipe also warns that some integrations may expose rough edges. Add @types/bun when you use Bun APIs, commit the lockfile, pin the Bun version in CI, and test your integration stack before migrating an existing project.

This repository uses Bun for build, performance-budget, and deployment scripts. That is a team-specific choice, not a requirement for Astro.

My take: I would not migrate a working project solely for a benchmark. I would adopt Bun when it simplifies the whole workflow and the integrations pass the same production checks.

See the Bun recipe.

TL;DR

Area Default worth keeping
Images Local imports through <Image />; priority only for the LCP hero
Fonts Self-host with the Fonts API; request and preload only what you use
Styling Tailwind v4 Vite plugin and CSS @theme, or scoped Astro CSS
Interactivity .astro, native HTML, and small scripts before framework islands
Hydration client:visible below the fold; client:load by exception
Navigation Deliberate prefetch; native transitions before <ClientRouter />
Content Typed collections, explicit sorting, MDX only when useful
Builds --timings, bundle reports, deferRender, and measured experiments
Quality astro check && astro build; structured logging
i18n and SEO Stable locale URLs, site, sitemap, consistent slashes, RSS
Deployment Static dist/ without an adapter unless you need a server
Tooling Bun when it fits the team; Node.js 22.23.4+ for current Astro

The State of JS 2025 survey placed Astro in the S-tier with a 94% satisfaction ratio—not #1 overall. That is encouraging sentiment data, not proof that Astro fits every project. Astro joined Cloudflare on January 16, 2026, while remaining open source and deployable elsewhere.

Frequently Asked Questions

Why use Astro instead of Next.js for content sites? Astro is HTML-first and ships no framework JavaScript for plain .astro components, hydrating only the islands you mark. Next.js is React-first and is a strong choice for application-heavy sites. For content-heavy pages, Astro usually gives you a smaller starting point, but third-party scripts and island choices still determine the final payload.

How do I configure Tailwind v4 in Astro 7? Run npx astro add tailwind to install @tailwindcss/vite, import tailwindcss in a global stylesheet, and use CSS-first @theme configuration. Remove the legacy @astrojs/tailwind integration when upgrading from Tailwind v3.

What is the difference between client:load and client:visible? client:load hydrates a component immediately; client:visible waits until it enters the viewport. Use client:visible for below-fold islands to avoid requesting their JavaScript before it is needed. Shared bundles may still be fetched earlier.

What changed in Astro 7? Astro 7 uses Vite 8, makes the Rust compiler and Sätteri Markdown pipeline defaults, stabilizes logging and route caching, and applies JSX whitespace rules. Astro 7.1 through 7.4 add lower-memory content loading, incremental builds, runtime loggers for extensions, build timings, and separate build and runtime image services. Current installation docs require Node.js 22.23.4 or higher.

How do I analyze an Astro bundle? Add rollup-plugin-visualizer to your Vite configuration and run a production build. Open the generated stats.html file, then use astro build --timings to find slow build phases. The visualizer shows site-wide dependencies, not the exact JavaScript downloaded by each page, so confirm findings in browser DevTools.

Should I use Bun with Astro? Bun is officially supported for creating, installing, developing, building, previewing, and testing Astro projects. It can be a good fit when your team already uses it, but Astro warns that some integrations may have rough edges. Add @types/bun for Bun APIs and verify your integration stack before migrating an existing project.

Sources


Tags: astro webdev javascript performance best-practices static-site-generation

Found this useful? Share it.

Related articles