Astro best practices for production come down to a few habits: keep pages static unless they truly need a server, ship JavaScript only through deliberate client:* directives or small scripts, validate all content with schemas, import images so Astro can optimize them, type your config and environment variables, and set site, a sitemap and per-page metadata from the first commit. Then automate checks so the site stays that way.
This guide lists the practices we’d apply to any Astro 7 site that real people depend on, grouped by area, with the config that implements each one.
Key Takeaways
- Default to static output. Opt individual routes into on-demand rendering only when they need request data.
- Treat every
client:*directive as a cost. Preferclient:visibleand plain scripts.- Define every collection with a loader and a Zod schema in
src/content.config.ts.- Use
astro:envfor environment variables so secrets can’t leak to the client.- Run
astro check, a link check and Lighthouse CI on every pull request.
Structure and configuration
Keep a predictable project structure
Use the conventional folders so anyone can find things:
src/
assets/ images that Astro optimizes
components/ ui/, sections/, layout/
content/ Markdown and MDX entries
layouts/ BaseLayout.astro, PostLayout.astro
lib/ plain TypeScript helpers
pages/ routes
styles/ tokens.css, global.css
content.config.ts
middleware.ts (only if needed)
public/ files served as-is: favicon, robots.txt
Put site-wide values (name, nav, social links) in one typed module such as src/config/site.ts, so a change happens once. The project structure explainer covers each folder.
A production-ready config
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
import sitemap from '@astrojs/sitemap';
export default defineConfig({
site: 'https://www.example.com',
trailingSlash: 'always',
prefetch: { defaultStrategy: 'hover' },
integrations: [sitemap()],
redirects: {
'/old-pricing/': '/pricing/',
},
env: {
schema: {
CONTACT_API_KEY: envField.string({ context: 'server', access: 'secret', optional: true }),
PUBLIC_ANALYTICS_ID: envField.string({ context: 'client', access: 'public', optional: true }),
},
},
});
Each line earns its place: site makes absolute URLs and the sitemap work, trailingSlash keeps URLs consistent, prefetch speeds up navigation, redirects preserve old links, and the env schema validates variables at startup. The config cheatsheet explains every option.
Pin versions and upgrade deliberately
Commit your lockfile and use exact or caret versions you have tested. Upgrade Astro on a branch, read the release post first, run npx @astrojs/upgrade to bump Astro and official integrations together, then run the full test suite. Upgrading one major version at a time is far easier than skipping several.
Rendering and JavaScript
Default to static, opt in to the server
Prerendered pages are the fastest and cheapest to serve, and have the fewest failure modes. Keep output at its default (static) and add export const prerender = false only on routes that need cookies, sessions or per-request data, with an adapter installed. The rendering mode guide walks through the decision.
Budget your JavaScript
Astro ships zero JavaScript by default. Keep it close to that:
- Write menus, tabs, accordions and copy buttons as
.astrocomponents with a small<script>. - Use framework islands only for stateful UI, and pick one framework for the whole site.
- Prefer
client:visibleorclient:idleoverclient:load. - Load heavy libraries with dynamic
import()on first interaction. - Load third-party tags (analytics, chat) as late as possible, or move them off the main thread with Partytown.
Check the client chunks in dist/_astro/ after each feature. A sudden jump in size is easy to catch then and hard to find months later. The island or script guide helps with the first decision.
Content
Validate everything with schemas
Every collection gets a loader and a schema:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';
const blog = defineCollection({
loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
schema: ({ image }) =>
z.object({
title: z.string().max(70),
description: z.string().min(50).max(160),
pubDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
cover: image().optional(),
draft: z.boolean().default(false),
}),
});
export const collections = { blog };
Length limits on titles and descriptions enforce SEO rules at build time. image() checks cover files exist. Drafts are filtered in one helper, so no page forgets the filter. The Zod frontmatter guide goes further.
Keep content out of components
Text editors will change belongs in Markdown, a collection or a config file, not hard-coded in component markup. That makes edits safe for non-developers and lets you move to a CMS later without touching layouts.
Images and fonts
Import images and use the Image component
Put images in src/assets/, import them, and render them with <Image /> or <Picture /> from astro:assets. Astro generates modern formats and responsive widths, and writes width and height so there’s no layout shift. Give the LCP image loading="eager" and fetchpriority="high"; let everything else lazy-load. The image cheatsheet lists the props.
Self-host fonts and limit weights
Use one or two families and only the weights you need. Self-host them (Astro’s Fonts API or @fontsource packages) instead of loading from a third-party origin, and preload the main text font. The self-hosted fonts guide covers both approaches.
Styling
- Store colors, spacing and fonts as CSS custom properties in one tokens file.
- Rely on Astro’s scoped styles for component CSS, and keep global CSS small.
- Accept and merge a
classprop withclass:listin reusable components. - Leave
build.inlineStylesheetsat its defaultauto, which inlines small stylesheets and links larger ones, unless measurements say otherwise.
SEO and accessibility
- One
SEO.astrocomponent renders title, description, canonical, Open Graph and Twitter tags on every page. - Add JSON-LD for articles, products, FAQs and breadcrumbs, rendered with
set:html={JSON.stringify(schema)}. - Generate a sitemap and
robots.txt, and submit the sitemap to Search Console. - Use real headings in order, labeled buttons, visible focus styles, and alt text on every meaningful image.
- Add a skip link and
langon the<html>element.
The Astro SEO checklist and the accessibility checklist cover both areas in depth.
Security
Static Astro sites have a small attack surface, but a few practices still matter:
- Declare secrets with
astro:envascontext: 'server', access: 'secret'so they can’t be imported into client code. - Leave
security.checkOriginat its defaulttrueon server-rendered sites, which rejects cross-site form posts. - Set security headers at your host (a
_headersfile on Cloudflare Pages or Netlify):Content-Security-Policy,X-Content-Type-Options,Referrer-Policy. - Consider Astro’s
security.cspoption, which generates hashes for Astro’s own scripts and styles. - Validate every form input on the server, with Zod schemas on Astro Actions.
The security checklist has the full list.
Quality checks and deployment
Automate the checks so they don’t depend on memory:
// package.json (excerpt)
{
"scripts": {
"check": "astro check",
"build": "astro check && astro build",
"preview": "astro preview",
"test": "vitest run"
}
}
On every pull request, run astro check, unit tests, a link check over dist/, and Lighthouse CI with performance and CLS budgets. Deploy from Git to a static host so each push produces a preview URL, and keep production deploys to the main branch. The Astro deploy guide compares hosts, and the deploy docs cover Netlify, Vercel and GitHub Pages.
Maintenance
- Review dependencies monthly; remove integrations you no longer use.
- Re-run Lighthouse and a crawl after any template change.
- Watch Search Console for indexing errors and Core Web Vitals regressions.
- Keep a short README covering how to run, build, deploy and add content.
These practices are easier to keep than to retrofit, which is the main argument for starting from a well-built base: an official starter, a maintained community theme, or one of the Komal Astro themes, which follow this static-first, typed approach. The official Astro docs remain the reference for every API mentioned here.
FAQ
What are the most important Astro best practices?
Keep pages static by default, ship JavaScript only where it’s needed, validate content with Zod schemas, import images for optimization, set site and add a sitemap, and use astro:env for secrets. Automate astro check and Lighthouse CI so the site stays healthy.
Should I use output server or static in Astro?
Use static, the default, for most sites. Turn on-demand rendering on for individual routes with export const prerender = false when they need request data like cookies or sessions. Only switch the whole site to output: 'server' when most routes need it.
How should I structure a large Astro project?
Group components by role (ui/, sections/, layout/), keep helpers in src/lib/, content in collections, site settings in a typed config module and tokens in one stylesheet. Use path aliases in tsconfig.json to keep imports short.
How do I keep an Astro site fast over time?
Set performance budgets in Lighthouse CI, review client JavaScript in dist/_astro/ after each feature, import every image through astro:assets, and self-host fonts. Check real-user Core Web Vitals in Search Console monthly.
How often should I upgrade Astro?
Apply patch and minor releases regularly, since they include fixes. Plan major upgrades on a branch after reading the release notes, using npx @astrojs/upgrade, and upgrade one major version at a time.