How to Create Pages and Layouts in Astro

How to Create Pages and Layouts in Astro

Master Astro's routing engine and layout composition patterns for enterprise-scale web applications. Learn advanced SSR, SSG, slots, and type safety.

Modern enterprise web engineering often faces an architectural paradox: applications require rich, dynamic user experiences, yet business metrics demand ultra-fast Core Web Vitals, bulletproof SEO, and minimal infrastructure overhead. Monolithic Single-Page Application (SPA) architectures frequently buckle under their own weight, shipping megabytes of blocking JavaScript downstream simply to render static document trees.

Astro addresses this paradigm by inverting the default rendering equation. By leveraging Islands Architecture and enforcing a zero-JavaScript-by-default baseline, Astro renders HTML on the server (or at build time) and only hydrates discrete interactive components on demand.

To scale an Astro application across large, distributed engineering teams, your foundational primitives—Pages and Layouts—must be architected with strict encapsulation, deterministic data flow, and complete type safety. This guide examines the mechanics of Astro’s routing engine and explores enterprise patterns for composing resilient layouts.


1. The Core Primitives: Pages vs. Layouts

In Astro, the distinction between a Page and a Layout is structural rather than categorical. Both use the .astro single-file component format containing a component script (---) and a component template. However, their architectural responsibilities diverge significantly:

src/
├── layouts/
│   ├── BaseLayout.astro         # Top-level DOM scaffolding (<head>, <body>, CDNs)
│   ├── MarketingLayout.astro    # Nested: Base + Global Nav + Footer
│   └── DashboardLayout.astro    # Nested: Base + Auth Guard + Sidebar + Telemetry
└── pages/
    ├── index.astro              # Canonical entrypoint (Route: /)
    ├── api/                     # API Endpoints (Data routes)
    │   └── v1/health.ts
    └── enterprise/
        └── [tenant]/
            └── settings.astro   # Dynamic route with parameterized context

The Anatomy of an Astro Component Execution Context

Unlike React or Vue components, the code inside an Astro component script runs exclusively on the server (either at build time during static site generation or per request during server-side rendering). It never executes in the client runtime.

---
// src/pages/reports.astro
// SERVER RUNTIME ONLY: Imports here are stripped from client bundles
import DashboardLayout from '@/layouts/DashboardLayout.astro';
import MetricDisplay from '@/components/react/MetricDisplay.tsx';
import { db } from '@/lib/database';
import { validateSession } from '@/lib/auth';

// Extract request-level metadata
const session = await validateSession(Astro.request);
if (!session.isValid) {
  return Astro.redirect('/login?code=UNAUTHORIZED', 302);
}

// Direct database/microservice I/O without an intermediate REST trip
const metrics = await db.telemetry.getAggregates({ tenantId: session.tenantId });
---

<DashboardLayout title="System Telemetry" user={session.user}>
  <section class="metrics-grid">
    <header>
      <h1>Cluster Health</h1>
      <p>Tenant: {session.tenantId}</p>
    </header>

    <!-- Hydration Boundary: Only this component ships JS to the browser -->
    <MetricDisplay client:idle data={metrics} />
  </section>
</DashboardLayout>

2. The File-Based Routing Engine

Astro utilizes a deterministic, filesystem-based routing engine rooted in the src/pages/ directory. The compiler maps file paths directly to Uniform Resource Identifiers (URIs).

Route Evaluation Hierarchy

When incoming requests resolve against file-system nodes, Astro applies a strict resolution matrix to prevent route ambiguity:

Incoming Request: /analytics/q3-summary
                  │
                  ▼
1. Static Match? ────────────────────────► [src/pages/analytics/q3-summary.astro]
                  │ (No)
                  ▼
2. Dynamic Parameter? ───────────────────► [src/pages/analytics/[reportId].astro]
                  │ (No)
                  ▼
3. Rest / Catch-all Parameter? ──────────► [src/pages/analytics/[...slug].astro]
                  │ (No)
                  ▼
4. Fallthrough Engine ───────────────────► [src/pages/404.astro]

Static Site Generation (SSG) with getStaticPaths

In pure SSG mode (output: 'static'), pages containing dynamic parameters must export a getStaticPaths() function. This function defines the boundary of all possible routes to pre-render at compile time.

For enterprise scale, ensure your data-fetching operations are deduplicated or batched to prevent I/O saturation against downstream origin services:

---
// src/pages/docs/[platform]/[...slug].astro
import type { GetStaticPaths, InferGetStaticPropsType } from 'astro';
import DocsLayout from '@/layouts/DocsLayout.astro';
import { cmsClient } from '@/lib/cms';

export const getStaticPaths = (async () => {
  // Query content topologies from headless CMS or internal knowledge base
  const documents = await cmsClient.getAllPublishedDocuments();

  return documents.map((doc) => ({
    params: {
      platform: doc.platform, // e.g., 'aws', 'gcp', 'azure'
      slug: doc.slug,         // e.g., 'networking/vpc-peering'
    },
    props: {
      document: doc,
    },
  }));
}) satisfies GetStaticPaths;

type Props = InferGetStaticPropsType<typeof getStaticPaths>;

const { document } = Astro.props;
---

<DocsLayout title={document.title} metaDescription={document.excerpt}>
  <article class="prose max-w-none">
    <h1>{document.title}</h1>
    <Fragment set:html={document.renderedHtml} />
  </article>
</DocsLayout>

Hybrid & Server-Side Rendering (SSR) Dynamic Routing

When operating in SSR mode (output: 'server') or Hybrid mode (output: 'hybrid'), dynamic routes are evaluated JIT (Just-In-Time). The getStaticPaths requirement is removed:

---
// src/pages/tenants/[tenantId]/billing.astro
import BaseLayout from '@/layouts/BaseLayout.astro';
import { BillingGateway } from '@/lib/billing';

// Opt out of pre-rendering if inside a hybrid application
export const prerender = false;

const { tenantId } = Astro.params;

if (!tenantId || !/^[a-z0-9-_]+$/i.test(tenantId)) {
  return new Response(null, {
    status: 400,
    statusText: 'Malformed Tenant Identifier',
  });
}

const ledger = await BillingGateway.fetchInvoices(tenantId);
---

<BaseLayout title={`Billing - ${tenantId}`}>
  <main>
    <h2>Invoice Ledger for {tenantId}</h2>
    <ul>
      {ledger.map((inv) => (
        <li>{inv.date}: ${(inv.amountCents / 100).toFixed(2)}</li>
      ))}
    </ul>
  </main>
</BaseLayout>

3. Advanced Layout Composition and Architectural Patterns

A common failure mode in frontend infrastructure is “layout sprawl,” where layouts tightly couple page-level state, analytics scripts, and arbitrary DOM elements. An enterprise layout architecture should enforce inversion of control using Astro’s <slot /> primitive.

The Slot Hierarchy

Astro slots mirror the Web Components Shadow DOM Slot API. They allow child nodes from a page to be projected into specific locations within a layout tree.

+-------------------------------------------------------+
|  BaseLayout.astro                                     |
|  +-------------------------------------------------+  |
|  | <head> Metadata, Favicons, CSS Variables        |  |
|  +-------------------------------------------------+  |
|  | <slot name="head" />                            |  |
|  +-------------------------------------------------+  |
|  | <body>                                          |  |
|  |   +-------------------------------------------+ |  |
|  |   | AppHeader.astro                           | |  |
|  |   +-------------------------------------------+ |  |
|  |   | <slot /> (Default page content projection)| |  |
|  |   +-------------------------------------------+ |  |
|  |   | <slot name="sidebar" />                   | |  |
|  |   +-------------------------------------------+ |  |
|  |   | AppFooter.astro                           | |  |
|  |   +-------------------------------------------+ |  |
|  | </body>                                         |  |
+--+-------------------------------------------------+--+

Implementing a Type-Safe Base Layout

Every enterprise application should feature a foundational layout that orchestrates dynamic meta tags, OpenGraph schemas, canonical links, and external asset prefetching.

---
// src/layouts/BaseLayout.astro
import '@/styles/tokens.css';
import '@/styles/global.css';

interface Props {
  title: string;
  description: string;
  canonicalUrl?: URL;
  ogImage?: string;
  noIndex?: boolean;
}

const {
  title,
  description,
  canonicalUrl = new URL(Astro.url.pathname, Astro.site),
  ogImage = '/assets/default-og.png',
  noIndex = false,
} = Astro.props;
---

<!doctype html>
<html lang="en" class="antialiased">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
    
    <!-- Primary Metadata -->
    <title>{title}</title>
    <meta name="description" content={description} />
    <link rel="canonical" href={canonicalUrl.toString()} />

    <!-- Robots -->
    {noIndex && <meta name="robots" content="noindex, nofollow" />}

    <!-- Open Graph / Social Engine -->
    <meta property="og:type" content="website" />
    <meta property="og:url" content={canonicalUrl.toString()} />
    <meta property="og:title" content={title} />
    <meta property="og:description" content={description} />
    <meta property="og:image" content={new URL(ogImage, Astro.site).toString()} />

    <!-- High-priority Resource Hints -->
    <link rel="preconnect" href="https://telemetry.enterprise.internal" crossorigin />

    <!-- Layout Extensibility Point for Page-Specific Head Elements -->
    <slot name="head" />
  </head>
  <body class="bg-surface text-on-surface">
    <div id="application-root" class="min-h-screen flex flex-col">
      <slot />
    </div>
  </body>
</html>

Nested Layout Composition: The Shell Strategy

Instead of building monolithic layouts that handle both marketing and authenticated surfaces, nest your specialized layouts within BaseLayout.astro.

---
// src/layouts/DashboardLayout.astro
import BaseLayout from './BaseLayout.astro';
import PrimaryNav from '@/components/navigation/PrimaryNav.astro';
import UserProfileFlyout from '@/components/navigation/UserProfileFlyout.vue';
import type { UserSession } from '@/types/auth';

interface Props {
  title: string;
  session: UserSession;
}

const { title, session } = Astro.props;
---

<BaseLayout title={`${title} | Enterprise Console`} description="Internal Operations Dashboard">
  <!-- Forward custom head tags up the tree if required -->
  <slot name="head" slot="head" />

  <header class="border-b border-outline px-6 py-4 flex justify-between items-center">
    <PrimaryNav role={session.role} />
    <!-- Island: Client interactivity triggered only when visible -->
    <UserProfileFlyout client:visible user={session} />
  </header>

  <div class="flex flex-1">
    <aside class="w-64 border-r border-outline p-4">
      <slot name="sidebar-nav" />
    </aside>

    <main class="flex-1 p-8">
      <!-- Default slot where the page body resolves -->
      <slot />
    </main>
  </div>
</BaseLayout>

To consume this nested layout, a page simply targets both the default and named slots:

---
// src/pages/admin/clusters.astro
import DashboardLayout from '@/layouts/DashboardLayout.astro';
import ClusterManager from '@/components/react/ClusterManager.tsx';
import SidebarNavigation from '@/components/navigation/SidebarNavigation.astro';
import { getAuthContext } from '@/lib/auth';

const authContext = await getAuthContext(Astro.request);
---

<DashboardLayout title="Kubernetes Fleet" session={authContext}>
  <!-- Inject into the named slot inside DashboardLayout -->
  <SidebarNavigation slot="sidebar-nav" context="infra" />

  <!-- Direct injection into the default slot -->
  <div class="space-y-6">
    <h1 class="text-2xl font-bold">Control Plane Clusters</h1>
    <ClusterManager client:load environment={authContext.environment} />
  </div>
</DashboardLayout>

4. Enterprise Data Passing and Edge Scenarios

Scaling out multi-team Astro codebases introduces challenges around state hydration, middleware injection, and UI boundaries.

Context Preservation via Astro.locals

A common antipattern is passing auth data, feature flags, or telemetry spans through deeply nested component props:

[Page Script] ──(prop)──► [DashboardLayout] ──(prop)──► [SubNav] ──(prop)──► [Avatar]

To break this coupling, inject contextual data directly at the network boundary using Astro Middleware (src/middleware.ts). This contextual data populates Astro.locals, which is accessible to all layouts and pages across the execution cycle:

// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { verifyJwt } from '@/lib/jwt';
import { metricsClient } from '@/lib/telemetry';

export const onRequest = defineMiddleware(async (context, next) => {
  const startTime = performance.now();
  const token = context.cookies.get('session-token')?.value;

  if (token) {
    try {
      context.locals.user = await verifyJwt(token);
    } catch {
      context.cookies.delete('session-token');
    }
  }

  // Trace execution time
  const response = await next();
  const duration = performance.now() - startTime;
  
  response.headers.set('Server-Timing', `app;dur=${duration.toFixed(2)}`);
  metricsClient.histogram('http_request_duration_ms', duration, {
    path: context.url.pathname,
  });

  return response;
});

Downstream in src/env.d.ts, define your domain types to ensure full TypeScript compiler coverage:

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

declare namespace App {
  interface Locals {
    user?: {
      id: string;
      email: string;
      role: 'admin' | 'operator' | 'auditor';
      tenantId: string;
    };
  }
}

Now, any Layout or Page can access the user without prop-drilling:

---
// src/layouts/AuditLayout.astro
const { user } = Astro.locals;

if (user?.role !== 'admin' && user?.role !== 'auditor') {
  return new Response('Forbidden', { status: 403 });
}
---
<div class="audit-wrapper">
  <span>Inspector: {user.email}</span>
  <slot />
</div>

5. Architectural Comparison: Astro vs. Traditional Frameworks

To evaluate Astro’s layout and routing engine for your technical stack, consider how it compares to other leading web frameworks:

Architectural Vector Astro Next.js (App Router) Remix / React Router v7
Routing Baseline File-based (Multi-Page Model) File-based with nested layout.js Flat-routes file or code config
Default JS Footprint 0 KB (HTML streaming) React Runtime + Server Action bundles React Runtime + Route manifests
Hydration Mechanics Selective Islands (client:*) Component-level Server/Client marks Route-level hydration
Layout Nesting Explicit slot composition Implicit folder hierarchy (layout.tsx) Explicit nested <Outlet /> tree
State Retention Per-document (MPA transition) Client-side routing cache Client-side memory cache
View Transitions Built-in Spec API abstraction Proprietary Router orchestration Standard SPA navigation

Astro offers a distinct advantage for platforms where read-heavy performance, documentation pipelines, and decoupled frontend islands are paramount.


6. Performance Pitfalls and Optimization Checklist

Even within a high-performance framework like Astro, large codebases can encounter architectural bottlenecks. Review this checklist before promoting pages and layouts to production:

[Enterprise Production Readiness]
 ├── Architectural Boundaries
 │   ├── [ ] Layouts NEVER orchestrate mutating database side-effects.
 │   ├── [ ] Layout prop interfaces strictly use TypeScript interfaces.
 │   └── [ ] Named slots provide default fallback content where sensible.
 ├── Hydration Optimization
 │   ├── [ ] Islands use the least aggressive directive (prefer client:visible/client:idle over client:load).
 │   └── [ ] Framework components (React/Vue/Svelte) do not wrap purely static marketing nodes.
 ├── Edge & Cache Strategies
 │   ├── [ ] In SSR mode, dynamic pages set explicit Cache-Control headers (s-maxage, stale-while-revalidate).
 │   └── [ ] Astro.locals is used instead of nested prop drilling for cross-cutting concerns.
 └── Asset Scoping
     ├── [ ] Global styles are exclusively imported within BaseLayout.
     └── [ ] Component styles leverage Astro's default scoped CSS to prevent stylesheet bloat.

Avoiding Slot Cascading Waterfalls

A subtle performance issue occurs when pages define nested async components inside slots:

<!-- ANTI-PATTERN: Async Layout Blocking -->
---
// MyLayout.astro
import CriticalData from './CriticalData.astro';
---
<html>
  <body>
    <!-- If CriticalData has a long-running top-level await, it stalls HTML streaming -->
    <CriticalData />
    <slot />
  </body>
</html>

To resolve this issue, parallelize your asynchronous data dependencies within the topmost page component via Promise.all(), then pass the resolved models directly to the layouts and downstream islands.

---
// src/pages/dashboard/index.astro
// FAST PATH: Run independent queries concurrently
const [userData, analyticsData] = await Promise.all([
  fetchUserData(Astro.request),
  fetchAnalyticsData()
]);
---
<DashboardLayout userData={userData}>
  <AnalyticsDisplay data={analyticsData} />
</DashboardLayout>

Conclusion

Astro redefines the boundaries of enterprise web application design by pairing the proven scalability of Multi-Page Applications with the component modeling, layout composition, and type safety of modern frontend stacks.

By treating pages as request orchestrators and layouts as structured, slot-driven design contracts, engineering organizations can deliver reliable, maintainable platforms that achieve near-perfect performance scores by default. When building your next enterprise web initiative, use pages to define what data exists, and use layouts to declare how that context is presented. This simple separation of concerns keeps your architecture clean, robust, and effortlessly scalable.