🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Astro Fundamentals••By Komal Nakrani

Astro Features You Probably Aren't Using (But Should)

Fourteen useful Astro features most projects skip: SVG components, collection references, server islands, Astro.rewrite, astro:env, middleware sequence and more.

#Astro#Astro Features#Components#Content Collections

The Astro features most projects skip are not experimental extras; they are stable APIs that remove whole categories of code. Importing SVGs as components, linking collection entries with reference(), deferring slow components with server:defer, rewriting requests with Astro.rewrite(), typed environment variables with astro:env, and persisting islands across navigation with transition:persist all ship in Astro 7 and take a few lines each.

Here are fourteen of them, each with a short example and the reason it is worth adopting.

Key Takeaways

  • Import an .svg file and use it as a component with props, no icon library needed.
  • Use reference() in collection schemas instead of matching IDs by hand.
  • Pass data from getStaticPaths() through props to avoid a second fetch per page.
  • server:defer renders slow, personalized parts of a page after the rest has loaded.
  • astro:env validates and types environment variables before the build runs.

Components and templates

1. SVG files as components

Import an SVG and render it like any Astro component. Props such as width, height, class and aria-label are applied to the <svg> element, and the markup is inlined at build time:

---
// src/components/Footer.astro
import GitHub from '../icons/github.svg';
---
<a href="https://github.com/withastro/astro">
  <GitHub width={20} height={20} aria-hidden="true" />
  <span>Astro on GitHub</span>
</a>

Inlined SVGs can use currentColor, so icons inherit the text color of their link. That replaces most icon packages for a small site.

2. class:list for conditional classes

class:list accepts strings, arrays and objects, drops falsy values, and deduplicates the result:

---
// src/components/Tab.astro
const { active, size = 'md' } = Astro.props;
---
<button class:list={['tab', `tab-${size}`, { 'is-active': active }]}><slot /></button>

No clsx dependency, no string concatenation bugs with stray spaces.

3. Fragment with set:html

When you have trusted HTML, such as a CMS rich-text field, render it without a wrapper element:

---
// src/components/RichText.astro
const { html } = Astro.props;
---
<Fragment set:html={html} />

Only use this with content you control or have sanitized, because set:html does not escape anything. The Fragment and set:html tip covers the details.

4. The Code component

<Code /> from astro:components highlights code with Shiki at build time, anywhere in a template, not just in Markdown:

---
// src/components/InstallSnippet.astro
import { Code } from 'astro:components';
---
<Code code="npm create astro@latest" lang="bash" />

Zero client JavaScript, the same themes as your Markdown code blocks.

Content and data

5. reference() between collections

Collections can point at each other, and Astro validates the link at build time:

// src/content.config.ts
import { defineCollection, reference } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const authors = defineCollection({
  loader: glob({ pattern: '**/*.json', base: './src/content/authors' }),
  schema: z.object({ name: z.string(), url: z.string().url().optional() }),
});

const blog = defineCollection({
  loader: glob({ pattern: '**/*.md', base: './src/content/blog' }),
  schema: z.object({
    title: z.string(),
    author: reference('authors'),
    related: z.array(reference('blog')).default([]),
  }),
});

export const collections = { authors, blog };

In a page, await getEntry(post.data.author) returns the full author entry, and await getEntries(post.data.related) returns the related posts. A typo in an author ID fails the build instead of rendering a blank byline. The Content Collections guide covers schemas in depth.

6. Props from getStaticPaths

Many projects fetch an entry in getStaticPaths() to build the params, then fetch it again in the page body. Pass it through instead:

---
// src/pages/blog/[id].astro
import { getCollection, render } from 'astro:content';

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

const { post } = Astro.props;
const { Content } = await render(post);
---
<Content />

One query instead of one per page. With a remote CMS, that difference shows up directly in build time. More in the getStaticPaths guide.

7. import.meta.glob for non-content files

Not everything belongs in a content collection. For a folder of components, images or data files, Vite’s import.meta.glob loads them all at once:

---
// src/pages/gallery.astro
import { Image } from 'astro:assets';
import type { ImageMetadata } from 'astro';

const images = import.meta.glob<{ default: ImageMetadata }>('../assets/gallery/*.{jpg,png}', { eager: true });
---
{Object.entries(images).map(([path, mod]) => (
  <Image src={mod.default} alt="" width={400} />
))}

Drop a new photo into the folder and it appears on the page, optimized, with no code change. Write real alt text when the images carry meaning.

Rendering and routing

8. Server islands with server:defer

On a page that is otherwise static, a personalized or slow component can render on demand after the page loads:

---
// src/pages/index.astro
import Recommendations from '../components/Recommendations.astro';
---
<Recommendations server:defer>
  <p slot="fallback">Loading recommendations…</p>
</Recommendations>

The page is served instantly from the CDN, and the island fetches its HTML separately. It requires an adapter. The server islands guide covers caching and props.

9. Astro.rewrite()

A rewrite serves a different route’s content without changing the URL or sending a redirect:

---
// src/pages/[...slug].astro (excerpt, on-demand route)
export const prerender = false;

const page = await findPage(Astro.params.slug);
if (!page) return Astro.rewrite('/404');
---

The visitor sees your real 404 page at the URL they requested, without a redirect hop. Check the status code in your browser’s network tab once, since that is what search engines read. Middleware has the same ability through context.rewrite() and next('/path').

10. transition:persist

With <ClientRouter />, an element marked transition:persist survives page navigation with its state intact:

---
// src/layouts/BaseLayout.astro (excerpt)
import AudioPlayer from '../components/AudioPlayer.jsx';
---
<AudioPlayer client:load transition:persist />

A playing video, an open chat widget or a form in progress stays put while the page around it changes. The View Transitions guide explains naming and transition:persist-props.

11. Prefetching

One config line makes links start loading before the click:

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

export default defineConfig({
  prefetch: { prefetchAll: true, defaultStrategy: 'hover' },
});

Use data-astro-prefetch="viewport" on key links to load them as soon as they scroll into view. The prefetch tip covers strategies and when to avoid them.

Configuration and tooling

12. Typed environment variables with astro:env

Declare variables once, and Astro validates them on startup, types them, and keeps secrets off the client:

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

export default defineConfig({
  env: {
    schema: {
      PUBLIC_API_URL: envField.string({ context: 'client', access: 'public' }),
      API_TOKEN: envField.string({ context: 'server', access: 'secret' }),
    },
  },
});
// src/lib/api.ts
import { API_TOKEN } from 'astro:env/server';

A missing variable fails immediately with a clear message instead of producing undefined in production. See the environment variables guide.

13. sequence() for middleware

Instead of one large middleware function, write small ones and chain them:

// src/middleware.ts
import { defineMiddleware, sequence } from 'astro:middleware';

const timing = defineMiddleware(async (context, next) => {
  const start = performance.now();
  const response = await next();
  response.headers.set('Server-Timing', `total;dur=${(performance.now() - start).toFixed(1)}`);
  return response;
});

const security = defineMiddleware(async (_context, next) => {
  const response = await next();
  response.headers.set('X-Content-Type-Options', 'nosniff');
  return response;
});

export const onRequest = sequence(timing, security);

Each piece is testable on its own, and the order is explicit. The middleware guide covers locals and auth patterns.

14. astro info and astro add

Two CLI commands save a lot of time. npx astro info prints your Astro version, package manager, adapter, integrations and OS, ready to paste into a bug report. npx astro add <integration> installs an integration and edits your config in one step, for example npx astro add sitemap or npx astro add react. The CLI cheatsheet lists the rest.

Where to start

You do not need all fourteen. A good order for most content sites is: props from getStaticPaths() (faster builds today), reference() (safer content), SVG components (fewer dependencies), and astro:env (fewer production surprises). Add server islands, rewrites and persistence when a page actually needs them.

Reading a complete project is the fastest way to see these patterns together. The official Astro docs cover each API, the folder structure docs show where each file lives, and you can open any of the Astro themes with a live preview to see how a finished site is put together.

FAQ

What are the most useful Astro features for beginners?

Start with content collections, the <Image /> component, class:list, and props from getStaticPaths(). They cover most content sites and need no extra packages.

Can Astro import SVG files as components?

Yes. Import the .svg file and render it as a component. Astro inlines the SVG markup and passes props such as width, height and class to the <svg> element.

What is the difference between Astro.rewrite and a redirect?

A redirect sends the browser to a new URL with a 3xx response. Astro.rewrite() renders another route’s content at the current URL, with no extra request and no URL change.

Do server islands work on a static Astro site?

The page itself stays static, but each server:defer component is rendered on demand, so the project needs an adapter installed for a host that can run server code.

Is the Astro Container API stable?

No. It is exported as experimental_AstroContainer from astro/container. It is useful for rendering components in tests, but its API may change between minor releases.