Astro¶
Scope: content-driven websites and web apps built with Astro, following the current (Astro 7) documentation: static and on-demand rendering, client and server islands, content collections, actions, middleware and sessions. UI framework components inside islands follow their own guidelines, such as React, Vue and Svelte. Framework-independent rules for accessibility, performance and security, such as WCAG, Core Web Vitals, sanitizing HTML before set:html (WEB-8) and security headers, are in Web front end, and deployment to Vercel, Netlify and Cloudflare is in Serverless and edge hosting. Actions, endpoints and middleware are backend code, so the Node.js and Security guidelines also apply to them.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 9 Astro Docs: the baseline. Project structure, components, routing, on-demand rendering, server islands, actions, middleware, sessions, content collections, images, environment variables, view transitions, testing and the configuration reference.
- 8 Islands architecture (Astro Docs): the core concept: static HTML by default, client islands that ship JavaScript only for interactive components, and server islands for dynamic or personalized parts of a page.
- 8 On-demand rendering (Astro Docs): adapters, prerendering by default, opting routes out of prerendering,
'server'output, HTML streaming, cookies and responses. - 7 Content collections (Astro Docs): build-time and live collections, loaders, Zod schemas, references between collections, querying and generating routes from content.
- 7 Actions (Astro Docs): type-safe backend functions with input validation, errors, form actions, and security for actions.
- 7 Using environment variables (Astro Docs): Vite's
PUBLIC_prefix and the type-safeastro:envschema with client, server and secret variables. - 7 Upgrade to Astro v7 (Astro Docs): the breaking changes in Astro 7, such as Vite 8, the Rust compiler, stable route caching and the new Markdown processor, with an upgrade command.
Key rules¶
Rendering and islands¶
- 7
ASTRO-1Keep Astro's default static output, and render a route on demand withexport const prerender = falseonly when it needs request data, such as cookies or a session. Switch tooutput: 'server'only when most pages are rendered on demand. Prerendered pages need no server function to render. (Astro, Enabling on-demand rendering, 'server' mode) - 7
ASTRO-2Add aclient:*directive only to framework components that must be interactive, and choose the lowest priority that works:client:idle,client:visibleorclient:mediafor most islands, andclient:loadonly for visible UI that must be interactive at once. Components without a directive render to HTML without JavaScript. This is how Astro followsWEB-5. (Astro, Client islands, Template directives: client directives) - 6
ASTRO-3Render personalized parts of an otherwise static or cached page as server islands withserver:deferand fallback content, pass them only the props they need, and set a constantASTRO_KEYfromastro create-keyfor rolling or multi-region deployments and CDN-cached pages. Props travel encrypted in a GET request that can be cached; when they make the URL longer than 2048 bytes, Astro sends a POST request that isn't cached. Without a constant key, a server can't decrypt props encrypted by another build. (Astro, Server island fallback content, Caching, Reusing the encryption key)
Content and assets¶
- 7
ASTRO-4Manage sets of structured content in content collections with a schema, and prefer build-time collections: use live collections only when content must be fresh on every request. Astro validates every entry against its schema and generates TypeScript types from it. (Astro, Defining the collection schema, Types of collections) - 6
ASTRO-5Keep local images insrc/and render them with<Image />or<Picture />fromastro:assets, and list only trusted remote hosts inimage.domainsorimage.remotePatterns. Astro optimizes these images and sets their dimensions, which prevents layout shift (WEB-6). Images inpublic/and from unlisted hosts aren't processed. (Astro, src/ vs public/,<Image />, Authorizing remote images)
Server code and security¶
- 9
ASTRO-6Treat every action as a public endpoint: give it aninputschema, and check authorization in its handler, not only in middleware or on the page that calls it. Astro serves each action at/_actions/<name>, so it needs the same checks as API endpoints and on-demand pages (SEC-1,SEC-10). Gating actions in middleware ensures only that a session exists. (Astro, Security when using actions, Authorize users from an action handler, Gate actions from middleware) - 9
ASTRO-7Declare environment variables in theenv.schemaof the Astro config, give a variablecontext: "client"or thePUBLIC_prefix only if its value may be public, and read secrets withaccess: "secret"fromastro:env/server. Public client variables end up in the client bundle; secret server variables aren't part of any bundle. This is how Astro followsSEC-11. (Astro, Variable types, Vite's built-in support) - 7
ASTRO-8Render every page that depends on the visitor, such as pages behind a login or with personalized content, on demand, and check authentication on each request in middleware or in the page. For prerendered pages, middleware runs once at build time, not on each request. (Astro, Middleware, On-demand rendering) - 7
ASTRO-9Pass request data, such as the current user, from middleware to pages and endpoints incontext.locals, and keep data that must last between requests in Astro sessions or a database.localslives for a single request, and sessions keep their data on the server instead of in cookies. This is how Astro followsSEC-12. Astro inlines the environment variables of a session driver's configuration into the build, so configure a driver that needs credentials in its own entrypoint file. (Astro, Storing data in context.locals, Sessions, Overriding the configuration at runtime) - 7
ASTRO-10Keepsecurity.checkOriginon, which is the default, and when a trusted proxy setsX-Forwarded-Host, list your hosts insecurity.allowedDomainsinstead of allowing all.checkOriginrejects cross-site form submissions to on-demand pages (CSRF,AUTH-17), and Astro ignoresX-Forwarded-Hostunless it matches an allowed domain, which prevents host header injection intoAstro.url. (Astro, security.checkOrigin, security.allowedDomains) - 7
ASTRO-11Turn onsecurity.csp, which adds hashes for Astro's own scripts and styles to a CSP<meta>element on every page, add your other directives in its options, and don't add'unsafe-inline'. Test it withastro buildandastro preview, because it doesn't work in the dev server. This is how Astro followsWEB-10. It doesn't support<ClientRouter />or Shiki, and with'unsafe-inline'in a directive Astro drops that directive's hashes. (Astro, security.csp, security.csp.directives)
Navigation and accessibility¶
- 6
ASTRO-12Prefer the browser's native cross-document view transitions, and add<ClientRouter />only for features that need it. With it, run code that must run on every page in anastro:page-loadlistener, and give every page a<title>, which the router announces to screen readers after each navigation. With the router, bundled scripts run only once per visit, and Astro's CSP doesn't support it. The router's announcement of the<title>is how Astro appliesWEB-22. (Astro, Differences between native view transitions and<ClientRouter />, Script re-execution, Route announcement)
Testing and tooling¶
- 7
ASTRO-13Type-check in CI withastro check, for example asastro check && astro build, and use thestrictorstrictesttsconfig template (TS-1). The dev server andastro builddon't type-check, andtscignores.astrofiles. (Astro, Type checking, tsconfig templates, astro check) - 6
ASTRO-14Test.astrocomponents with Vitest throughgetViteConfig()and the Container API, and run end-to-end tests with Playwright against a production build served byastro preview. The Container API is still experimental and can change in minor releases. Follow the test rules in Web front end, such asWEB-14toWEB-17. (Astro, Vitest and Container API, Playwright: launching a web server during the tests, Container API)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 astro check: runs diagnostics, including type-checking
.astroand.tsfiles, and exits with code 1 when it finds errors; with--minimumFailingSeverity warning, warnings fail it too. ChecksASTRO-13. - 7 Content collection schema validation: built into Astro, which reports an error when a collection entry doesn't match its schema. Partly checks
ASTRO-4. - 6 eslint-plugin-astro:
astro/no-unsafe-inline-scriptsflags inline scripts, which typically need'unsafe-inline'in a CSP, andastro/no-set-html-directiveflags everyset:html, the unescaped HTML sink thatWEB-8covers. Partly checksASTRO-11. - 5
astro:envvalidation: built into Astro, which raises an error when a variable declared withaccess: "secret"matches a prefix invite.envPrefix, which would expose it in client bundles, and when variables don't match their schema. Partly checksASTRO-7.
Tutorials and further reading¶
- 7 Build your first Astro blog (Astro Docs): the official tutorial, which builds and deploys a blog with pages, components, layouts, content and an interactive island.
- 7 Islands Architecture (Jason Miller, 2020): the article that described the islands pattern Astro builds on: server-rendered HTML with independently hydrated widgets.