Astro Project Structure Explained: A Guide for Beginners

Astro Project Structure Explained: A Guide for Beginners

Master the Astro project layout. Explore directory conventions, content collections, hybrid routing, island architecture, and enterprise best practices.

Enterprise frontend architecture has undergone a decisive paradigm shift. For nearly a decade, single-page application (SPA) frameworks treated the browser as an operating system, downloading massive JavaScript runtimes before rendering a single pixel. Astro upends this model by resurrecting the multi-page application (MPA) enhanced with Islands Architecture—yielding zero client-side JavaScript by default, fast Time to Interactive (TTI), and isolated component hydration.

Transitioning to Astro requires unlearning SPA habits. Its file system is not merely an arbitrary organizational suggestion; it is a compiled boundary engine that informs routing, asset optimization, build targets, and client execution contexts.

This guide provides an architectural breakdown of the standard Astro project structure, illustrating how code flows from disk to the compiler, and ultimately to the browser or edge runtime.


Architectural Overview: The Enterprise Astro Workspace

At a macroscopic level, Astro organizes files into three main strata: unprocessed assets, compile-time pipeline code, and build orchestration configurations.

Here is the anatomy of a production-grade Astro repository:

├── .astro/                     # Ephemeral TypeScript definitions & compiler caches
├── public/                     # Static, unprocessed assets served directly at root
├── src/                        # The engine room (processed via Vite and Astro compiler)
│   ├── assets/                 # Processed media (optimized via Vite/Sharp)
│   ├── components/             # Reusable UI units (Astro, React, Svelte, Vue)
│   │   ├── islands/            # Hydrated dynamic client components
│   │   └── static/             # Pure Astro zero-JS components
│   ├── content/                # Type-safe content collections (MD, MDX, JSON, YAML)
│   │   └── config.ts           # Schema validation via Zod
│   ├── env.d.ts                # Ambient TypeScript typings for Astro runtime
│   ├── layouts/                # Base document scaffolds (HTML shells & slots)
│   ├── middleware.ts           # Edge/Server request interceptors
│   ├── pages/                  # File-system routing (Pages, API endpoints, dynamic routes)
│   ├── styles/                 # Global styles, Tailwind configurations, design tokens
│   └── utils/                  # Domain logic, helpers, and pure TypeScript modules
├── astro.config.mjs            # Core framework, integrations, and adapter setup
├── package.json                # Dependencies, package metadata, and scripts
└── tsconfig.json               # TypeScript compiler configuration (strict mode)

To understand why this directory layout is designed this way, we must examine how Astro parses these directories during its build and server-render lifecycles.

       [ Client Request ]
               │
               ▼
      [ src/middleware.ts ] ─── (Auth, Headers, Context mutation)
               │
               ▼
        [ src/pages/ ] ──────── (File-system router resolves route)
         ├── .astro (Compiles static HTML skeleton via src/layouts/)
         └── .ts    (Executes API endpoint / returns JSON or Response)
               │
               ▼
      [ src/components/ ] ───── (Renders server-side HTML)
         ├── Static (.astro) -> Pure HTML string
         └── Island (.tsx)   -> Inlines HTML + client directive hydration payload
               │
               ▼
      [ Output HTML Stream ] ── Sent to client with minimal/zero JS

The Root Configuration Layer

Before diving into the /src folder, an engineer must grasp the configuration files that dictate how the Astro compiler transforms project source code.

astro.config.mjs

The root configuration file serves as the centralized manifest for your application’s integrations, deployment target, and build pipeline. Astro is built on top of Vite, meaning Vite plugins and configurations can be injected directly into this file.

// astro.config.mjs
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
import tailwind from '@astrojs/tailwind';
import node from '@astrojs/node';

export default defineConfig({
  // Defines the deployment runtime mode
  // 'static' = pure SSG; 'server' = SSR on every request; 'hybrid' = SSG default with opt-in SSR
  output: 'hybrid',
  
  // Adapter determines the runtime layer (e.g., Node, Cloudflare, Vercel)
  adapter: node({
    mode: 'standalone',
  }),

  // Integrations extend Astro with frameworks and libraries
  integrations: [
    react({
      include: ['**/islands/**'], // Restrict React compilation boundary
    }),
    tailwind({
      applyBaseStyles: false,
    }),
  ],

  // Scoped Vite overrides for enterprise module resolution
  vite: {
    resolve: {
      alias: {
        '@': '/src',
      },
    },
    build: {
      cssMinify: 'lightningcss',
    },
  },
});

tsconfig.json

Astro features first-class TypeScript support. The tsconfig file extends Astro’s strict base configurations to ensure that types inside .astro files and dynamic routes maintain end-to-end type safety:

{
  "extends": "astro/tsconfigs/strict",
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

The .astro/ Directory

Introduced in recent versions of Astro, the .astro/ folder contains generated types—specifically metadata derived from the Content Collections engine. You should include .astro/ in your .gitignore. It is generated automatically when running astro dev, astro build, or astro sync.


The Static Asset Duality: /public vs. /src/assets

One common point of confusion for engineers adopting Astro is where static assets should live. Astro splits assets between two directories:

Feature / Attribute /public /src/assets
Vite Processing Skipped entirely Processed, hashed, deduplicated
Image Optimization None (served raw) Transformed to WebP/AVIF, resized
Import Semantics Referenced via absolute string (/logo.svg) Imported as ES Modules (import logo from ...)
Cache Busting Manual (Query strings) Automatic content hashing
Ideal For robots.txt, favicon.ico, manifest.json Core UI graphics, layout media, hero images

Working with /src/assets

When an image is located inside /src/assets/, you leverage Astro’s built-in optimization engine, which invokes Sharp at build time:

---
// src/components/UserAvatar.astro
import { Image } from 'astro:assets';
import corporateLogo from '../assets/branding/enterprise-logo.png';
---

<div class="avatar-container">
  {/* The Image component automatically resizes, optimizes, and generates AVIF/WebP */}
  <Image 
    src={corporateLogo} 
    alt="Corporate Branding Logo" 
    width={400} 
    quality="high"
    loading="eager" 
  />
</div>

Assets placed in /public, by contrast, bypass this pipeline entirely. If you put corporate-logo.png into /public, the compiler will not generate optimized formats or resize the file; it will be served verbatim at https://example.com/corporate-logo.png.


Inside the Core Engine: /src

The /src folder contains your project’s executable source code. Astro enforces strict semantics on some subdirectories (pages/, content/), while others (components/, layouts/, styles/) are conventions that streamline clean architecture.

1. src/pages/: File-System Routing and API Endpoints

Astro routes derive their URIs from the layout of the src/pages/ folder. This directory handles three distinct patterns:

  • Static & Dynamic Pages (.astro, .md, .mdx)
  • API Endpoints (.ts, .js)
  • Dynamic Parameter Routes ([param].astro, [...catchall].astro)

Example: Hybrid Page Routing with SSR Override

By setting output: 'hybrid' in your Astro config, all pages compile to static HTML at build time by default. However, any route can opt into server-side rendering on demand:

---
// src/pages/dashboard/[orgId].astro

// Instruct the Astro compiler to process this route dynamically per-request
export const prerender = false;

const { orgId } = Astro.params;
const sessionCookie = Astro.cookies.get('session');

if (!sessionCookie) {
  return Astro.redirect('/login');
}

// Fetch dynamic, secure enterprise telemetry at runtime
const telemetryData = await fetch(`https://api.internal/metrics/${orgId}`, {
  headers: { Authorization: `Bearer ${sessionCookie.value}` }
}).then(res => res.json());
---

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Org Telemetry - {orgId}</title>
  </head>
  <body class="bg-slate-900 text-white">
    <main class="p-8">
      <h1>Organization Metrics: {orgId}</h1>
      <pre>{JSON.stringify(telemetryData, null, 2)}</pre>
    </main>
  </body>
</html>

Example: Type-Safe API Endpoints

Astro is not just a UI framework; it can run serverless and edge functions directly through its routing system. An API endpoint is established by exporting functions named after HTTP verbs from a .ts file:

// src/pages/api/v1/health.ts
import type { APIRoute } from 'astro';

export const prerender = false; // Execute dynamically on every request

export const GET: APIRoute = async ({ request }) => {
  const telemetry = {
    uptime: process.uptime(),
    status: 'HEALTHY',
    timestamp: new Date().toISOString(),
  };

  return new Response(JSON.stringify(telemetry), {
    status: 200,
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 'no-cache, no-store',
    },
  });
};

2. src/layouts/: Base Structural Shells

Layouts are reusable .astro components designed to wrap full pages. They typically house the Document Type Definition (<!DOCTYPE html>), <head> boilerplate, metadata pipelines, and shared UI regions like headers, navigation bars, and footers.

Layouts make heavy use of Astro’s <slot /> mechanic, which behaves identically to the native Web Components <slot> element.

---
// src/layouts/BaseLayout.astro
interface Props {
  title: string;
  description?: string;
}

const { 
  title, 
  description = "Enterprise Cloud Services Platform" 
} = Astro.props;
---

<!DOCTYPE html>
<html lang="en" class="h-full bg-gray-50">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content={description} />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    <title>{title}</title>
  </head>
  <body class="min-h-full flex flex-col">
    <header class="w-full border-b bg-white p-4">
      <slot name="header">
        <!-- Default fallback content if slot isn't populated -->
        <span class="font-bold text-lg">Default Enterprise Header</span>
      </slot>
    </header>

    <main class="flex-grow p-6">
      {/* Default slot for main page content */}
      <slot />
    </main>

    <footer class="p-4 bg-gray-100 text-center text-sm text-gray-500">
      &copy; {new Date().getFullYear()} Corporation Inc. All rights reserved.
    </footer>
  </body>
</html>

3. src/components/: Islands Architecture in Practice

The components/ directory demonstrates Astro’s core strength: framework-agnostic composition.

Inside this directory, engineers can write .astro components, alongside React (.tsx), Svelte (.svelte), or Vue (.vue) files. Astro treats all components as pure HTML compilers by default. If a component is written in React, Astro will strip the React client-side runtime completely during the build, rendering purely static markup.

Client-side JavaScript is only shipped when explicitly declared via a Client Directive.

Component Tree Execution:

Page Layout (src/layouts/BaseLayout.astro)
│
├── StaticHeader (src/components/Header.astro)
│   └── Output: Pure HTML, 0 KB JavaScript
│
├── SearchInput (src/components/islands/Search.tsx)
│   ├── Directive: client:idle
│   └── Output: HTML + JS hydrated when main thread is idle
│
└── InteractiveChart (src/components/islands/Chart.vue)
    ├── Directive: client:visible
    └── Output: HTML + JS hydrated only when scrolled into view

Hydration Directives Explained

When consuming interactive components inside an Astro file, client directives define the hydration contract:

---
// src/pages/index.astro
import BaseLayout from '../layouts/BaseLayout.astro';
import StaticBanner from '../components/static/Banner.astro';

// Framework Islands
import RealtimeStockTicker from '../components/islands/RealtimeStockTicker.tsx';
import SupportDrawer from '../components/islands/SupportDrawer.vue';
---

<BaseLayout title="Executive Overview">
  <!-- 0 KB JavaScript overhead -->
  <StaticBanner greeting="Welcome to the Platform" />

  <!-- Critical Island: Hydrate immediately upon initial page load -->
  <RealtimeStockTicker client:load symbol="MSFT" />

  <!-- Secondary Island: Hydrate only when viewport scrolls to this element -->
  <SupportDrawer client:visible />
</BaseLayout>
  • client:load: Hydrates immediately. Use exclusively for mission-critical, interactive elements (e.g., global navigation drawers, auth controls).
  • client:idle: Hydrates when the browser is finished with initial page tasks (utilizing requestIdleCallback).
  • client:visible: Hydrates only when the element intersects the browser viewport (utilizing IntersectionObserver).
  • client:media="(min-width: 1024px)": Hydrates only when matching a CSS media query.
  • client:only="react": Skips server-side rendering entirely; renders solely on the client. Useful for components with hard window or document dependencies.

4. src/content/: Type-Safe Content Collections

For corporate documentation, engineering blogs, knowledge bases, or marketing content, Astro provides the Content Collections API. Located inside src/content/, this subsystem treats Markdown and MDX files like a structured, typed, local database.

The cornerstone of this pattern is src/content/config.ts, which enforces compile-time schemas via Zod.

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

const changelogCollection = defineCollection({
  type: 'content', // 'content' for MD/MDX, 'data' for JSON/YAML
  schema: z.object({
    title: z.string().max(80),
    version: z.string().regex(/^\d+\.\d+\.\d+$/),
    releaseDate: z.date(),
    author: z.object({
      name: z.string(),
      email: z.string().email(),
    }),
    tags: z.array(z.string()).default(['maintenance']),
    isCritical: z.boolean().default(false),
  }),
});

export const collections = {
  'changelog': changelogCollection,
};

When authoring an entry in src/content/changelog/v2.1.0.md, Astro guarantees that the frontmatter adheres directly to this contract:

---
title: "Distributed Edge Syncing Engine Update"
version: "2.1.0"
releaseDate: 2024-03-25
author:
  name: "Platform Engineering"
  email: "platform@company.internal"
tags: ["networking", "edge", "latency"]
isCritical: true
---

## Summary of Changes

This release patches cache coherency issues observed at edge network termination points...

To fetch this collection inside any page, Astro exposes the getCollection query API:

---
// src/pages/changelog/index.astro
import { getCollection } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';

// Type is inferred directly from the Zod schema defined in config.ts
const releases = await getCollection('changelog', ({ data }) => {
  return data.isCritical === true;
});
---

<BaseLayout title="Critical System Updates">
  <ul>
    {releases.map(release => (
      <li>
        <a href={`/changelog/${release.slug}`}>
          <h3>{release.data.title} (v{release.data.version})</h3>
          <p>Released: {release.data.releaseDate.toLocaleDateString()}</p>
        </a>
      </li>
    ))}
  </ul>
</BaseLayout>

If a developer introduces a typos or invalid frontmatter (e.g., passing a string for isCritical instead of a boolean), Astro halts the build pipeline immediately with detailed compiler errors.


5. src/middleware.ts: The Enterprise Request Interceptor

For applications running in SSR or Hybrid modes, Astro provides a centralized pipeline to execute logic prior to rendering pages or executing API routes. The middleware runs on the server or edge runtime and is placed at src/middleware.ts.

It intercept operations such as authentication validation, security header injections, and context augmentation:

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

export const onRequest = defineMiddleware(async (context, next) => {
  const startTime = performance.now();
  
  // Example: Contextual Auth Verification
  const token = context.cookies.get('enterprise_jwt')?.value;
  
  if (context.url.pathname.startsWith('/admin') && !token) {
    // Intercept and short-circuit to redirect
    return context.redirect('/auth/unauthorized', 302);
  }

  // Inject shared state via context.locals (typed via env.d.ts)
  context.locals.requestId = crypto.randomUUID();
  context.locals.isAuthenticated = Boolean(token);

  // Pass execution down the pipeline to the next middleware or route
  const response = await next();

  // Post-execution mutations: append security and telemetry headers
  const executionTime = (performance.now() - startTime).toFixed(2);
  response.headers.set('X-Response-Time', `${executionTime}ms`);
  response.headers.set('X-Content-Type-Options', 'nosniff');
  response.headers.set('X-Frame-Options', 'DENY');

  return response;
});

To type-check values added to context.locals, augment the App.Locals interface inside src/env.d.ts:

// src/env.d.ts
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />

declare namespace App {
  interface Locals {
    requestId: string;
    isAuthenticated: boolean;
  }
}

Architectural Scaling: Domain-Driven Layouts

As an Astro project scales to hundreds of routes and dozens of cross-functional contributors, keeping all components in a flat src/components/ directory can degrade codebase maintainability.

Enterprise architectures often shift to a Domain-Driven Design (DDD) or Vertical Slice directory structure within /src. Astro easily accommodates this without breaking its routing conventions:

src/
├── domains/                      # Domain-specific components, types, and logic
│   ├── auth/
│   │   ├── components/           # AuthForm.astro, OAuthProviderList.tsx
│   │   ├── services/             # authService.ts
│   │   └── types/                # index.ts
│   └── billing/
│       ├── components/           # PricingCard.astro, PaymentModal.vue
│       ├── hooks/                # useStripeSession.ts
│       └── utils/                # taxCalculators.ts
├── layouts/                      # Shared global document shells
├── pages/                        # Thin glue layer (Pages only map to domain components)
│   ├── auth/
│   │   └── login.astro           # Imports <AuthForm /> from src/domains/auth
│   └── billing/
│       └── checkout.astro        # Imports <PaymentModal /> from src/domains/billing
└── middleware.ts

In this model, files within src/pages/ remain intentionally thin. They act strictly as controllers that extract route parameters, query data via content collections or services, and assemble high-level domain components.

---
// src/pages/billing/checkout.astro
import BaseLayout from '@/layouts/BaseLayout.astro';
import PricingMatrix from '@/domains/billing/components/PricingMatrix.astro';
import CheckoutFlow from '@/domains/billing/components/CheckoutFlow.tsx';

export const prerender = false; // Evaluated dynamically
---

<BaseLayout title="Upgrade Enterprise Subscription">
  <div class="checkout-grid">
    <PricingMatrix />
    <!-- React Island handling PCI-compliant iframe injection -->
    <CheckoutFlow client:load />
  </div>
</BaseLayout>

Best Practices Checklist for Enterprise Astro Projects

To ensure your Astro codebase remains resilient, performant, and maintainable over time, follow this baseline architectural checklist:

  1. Keep src/pages/ Clean: Avoid nesting extensive UI markup, complex business logic, or multiple inline sub-components within routing files. Delegate to layouts and domain components.
  2. Strictly Quarantine Hydrated Islands: Keep components using client:* directives as small and as deep in the DOM tree as possible. Passing static HTML into hydrated components via <slot /> prevents unnecessary hydration cascades.
  3. Always Validate Frontmatter: Place all marketing and long-form structured content inside src/content/ and declare rigorous schemas in src/content/config.ts.
  4. Leverage /src/assets for Processing: Only use /public for unprocessable root-level metadata files (robots.txt, favicon.svg). Run application imagery through astro:assets to minimize cumulative layout shift (CLS) and save bandwidth.
  5. Use middleware.ts for Cross-Cutting Concerns: Avoid duplicating auth checks, tracking logic, or security header assignments inside individual routes. Implement them once in the middleware layer.

Conclusion

Astro’s project structure directly mirrors its architectural philosophy: fast, static delivery by default, with dynamic capabilities layered on only when required.

By establishing a clear mental separation between static compilation boundaries (/public, .astro components) and dynamic execution surfaces (middleware.ts, src/pages/api/, and islands/), engineering teams can construct enterprise web platforms that maximize core web vitals, drastically reduce bundle sizes, and keep codebases clean and scalable.