astro

This skill provides essential Astro framework patterns, focusing on server-side rendering (SSR), static site generation (SSG), middleware, and TypeScript best practices. It helps AI agents implement secure authentication, manage API routes, and debug rendering behaviors within Astro projects.

159 stars
Complexity: easy

About this skill

The Astro Framework Skill equips AI coding agents with a deep understanding of core Astro development concepts. It details the nuances of rendering modes, contrasting Static Site Generation (SSG) with Server-Side Rendering (SSR), particularly concerning protected content. The skill highlights the critical insight that pre-rendered (SSG) pages bypass middleware, making SSR (`prerender = false`) essential for pages and API routes requiring runtime authentication or access control. It provides actionable code patterns for implementing robust authentication using `Astro.locals` within pages and API routes. The skill also covers effective middleware configuration, demonstrating how to use tools like Clerk for route protection and user session management. By leveraging this skill, an AI agent can correctly architect Astro applications, ensuring that sensitive data and functionalities are properly secured and rendered according to specific requirements. This skill is invaluable for AI agents tasked with developing, extending, or debugging Astro applications. It consolidates crucial architectural knowledge, allowing the agent to generate accurate and secure Astro code, avoid common pitfalls related to rendering and authentication, and adhere to best practices for building modern web experiences.

Best use case

This skill is primarily used by AI coding agents when developing or modifying Astro applications that require secure user authentication, role-based access control, or specific rendering strategies for different types of content. It is most beneficial for agents working on e-commerce platforms, membership sites, learning portals, or any web application where content protection and dynamic server-side logic are paramount.

This skill provides essential Astro framework patterns, focusing on server-side rendering (SSR), static site generation (SSG), middleware, and TypeScript best practices. It helps AI agents implement secure authentication, manage API routes, and debug rendering behaviors within Astro projects.

The AI agent will produce correct Astro code patterns for secure authentication, proper middleware integration, and optimal rendering mode selection for various content and API routes.

Practical example

Example input

Help me create a new Astro page `/dashboard` that is only accessible to authenticated users using Clerk, and ensure it's not pre-rendered.

Example output

```typescript
// src/pages/dashboard.astro
---
export const prerender = false; // Ensures middleware runs on every request

const auth = Astro.locals.auth();
if (!auth?.userId) {
  return Astro.redirect('/sign-in'); // Redirect unauthenticated users
}
---

<h1>Welcome to your secure Dashboard!</h1>
```

When to use this skill

  • Developing new Astro pages or API routes that require user authentication or access control.
  • Implementing or debugging Astro middleware for route protection or session management.
  • Deciding between SSG and SSR for different parts of an Astro application, especially for protected content.
  • Troubleshooting rendering issues or unexpected access to content in an Astro project.

When not to use this skill

  • Working on projects that are not built with the Astro framework.
  • Tasks completely unrelated to web development, rendering, or authentication logic.
  • When the primary goal is basic UI styling or static content without dynamic server-side needs.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/astro/SKILL.md --create-dirs "https://raw.githubusercontent.com/majiayu000/claude-skill-registry/main/skills/development/astro/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/astro/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How astro Compares

Feature / AgentastroStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

This skill provides essential Astro framework patterns, focusing on server-side rendering (SSR), static site generation (SSG), middleware, and TypeScript best practices. It helps AI agents implement secure authentication, manage API routes, and debug rendering behaviors within Astro projects.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Astro Framework Skill

Patterns and gotchas for Astro development, with focus on authentication, middleware, and rendering modes.

## Rendering Modes

### SSG vs SSR for Protected Content

**Critical**: In Astro 5.x with `output: "static"`, pre-rendered pages bypass middleware completely.

```
User Request → Vercel CDN → Pre-rendered HTML (cached)
                         ↳ Middleware SKIPPED for static content
```

| Rendering Mode | Middleware Runs? | Use Case |
|----------------|------------------|----------|
| SSG (`prerender = true`) | **No** - build time only | Public content, marketing |
| SSR (`prerender = false`) | **Yes** - every request | Protected content, auth |

### Protecting Content Pages

```typescript
// src/pages/learn/[workshop]/[slug].astro
---
// REQUIRED: Forces middleware to run on every request
export const prerender = false;

const auth = Astro.locals.auth();
if (!auth?.userId) {
  return Astro.redirect('/sign-in');
}
---
```

### API Routes Always Need SSR

```typescript
// src/pages/api/members/index.ts
// API routes needing locals.auth MUST disable prerender
export const prerender = false;

export const GET: APIRoute = async ({ locals }) => {
  const auth = locals.auth?.();
  if (!auth?.userId) {
    return new Response("Unauthorized", { status: 401 });
  }
  // ...
};
```

## Middleware Patterns

### Basic Route Protection

```typescript
// src/middleware.ts
import { clerkMiddleware, createRouteMatcher } from "@clerk/astro/server";

const isPublicRoute = createRouteMatcher([
  "/",
  "/sign-in(.*)",
  "/sign-up(.*)",
  "/api/webhooks/(.*)",
]);

export const onRequest = clerkMiddleware((auth, context) => {
  const { userId } = auth();

  if (isPublicRoute(context.request)) {
    return; // Allow public routes
  }

  if (!userId) {
    return auth().redirectToSignIn();
  }
});
```

### Member Status Validation

Check member status in addition to authentication:

```typescript
import { checkMemberAccess, ACCESS_LEVELS } from "@lib/auth";

async function checkAccess(userId, context) {
  const member = await memberQueries.findByClerkId(userId);

  if (!member) {
    return context.redirect("/pending-approval");
  }

  // Check status (expired, pending_approval, etc.)
  const access = checkMemberAccess(member, ACCESS_LEVELS.MEMBER);
  if (!access.hasAccess && access.redirectTo) {
    return context.redirect(access.redirectTo);
  }

  return undefined; // Allow access
}
```

## TypeScript Gotchas

### Unused Variable in Template Strings

Astro's TypeScript preprocessor may report variables as "unused" even when used in template literals:

```typescript
// ❌ TypeScript error: 'slug' is declared but never read
---
const slug = entries[0]?.slug.split("/").pop();
return Astro.redirect(`/learn/${workshop}/${slug}`);
---

// ✅ Inline the expression
---
return Astro.redirect(`/learn/${workshop}/${entries[0]?.slug.split("/").pop() ?? "default"}`);
---
```

### Path Brackets in Shell Commands

File paths with brackets need quoting in shell:

```bash
# ❌ Shell interprets brackets as glob
git add src/pages/learn/[workshop]/index.astro

# ✅ Quote the path
git add 'src/pages/learn/[workshop]/index.astro'
```

## Content Collections

### Dynamic Routes with SSR

When using SSR, you can't use `getStaticPaths()`. Use direct lookups instead:

```typescript
// ❌ SSR mode - getStaticPaths not available
export const prerender = false;
export function getStaticPaths() { ... } // Won't work

// ✅ Direct content lookup
export const prerender = false;
const { workshop, slug } = Astro.params;
const entry = await getEntry("workshops", `${workshop}/${slug}`);
if (!entry) {
  return Astro.redirect("/404");
}
```

## Cache Headers

### Prevent Caching of Status Pages

Status pages (pending, expired, error) should never be cached:

```typescript
---
// Prevent caching - status can change
Astro.response.headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
Astro.response.headers.set("Pragma", "no-cache");
---
```

## Configuration Reference

### astro.config.mjs

```javascript
export default defineConfig({
  output: "static",  // Default - SSG with per-page SSR opt-in
  // OR
  output: "server",  // Full SSR - all pages server-rendered

  adapter: vercel(), // Required for SSR on Vercel
});
```

### Per-Page Rendering

```typescript
// Force SSG (build-time)
export const prerender = true;

// Force SSR (request-time)
export const prerender = false;
```

## Common Issues

### Middleware Not Running

**Symptoms**: Auth checks bypassed, expired users see content

**Cause**: Page is pre-rendered (SSG default)

**Fix**: Add `export const prerender = false;`

### 404 on Dynamic Routes

**Symptoms**: `/learn/workshop/module` returns 404

**Cause**: Dynamic params not handled in SSR mode

**Fix**: Check `Astro.params` and handle missing values:
```typescript
const { workshop, slug } = Astro.params;
if (!workshop || !slug) {
  return Astro.redirect("/404");
}
```

### Build Fails with Type Errors

**Symptoms**: `ts(6133): variable is declared but never read`

**Cause**: Astro preprocessor quirk with template strings

**Fix**: Inline expressions or suppress with `// @ts-ignore`

---

*Last updated: December 2025*

Related Skills

chrome-debug

159
from majiayu000/claude-skill-registry

This skill empowers AI agents to debug web applications and inspect browser behavior using the Chrome DevTools Protocol (CDP), offering both collaborative (headful) and automated (headless) modes.

Coding & DevelopmentClaude

laravel-expert

31392
from sickn33/antigravity-awesome-skills

Senior Laravel Engineer role for production-grade, maintainable, and idiomatic Laravel solutions. Focuses on clean architecture, security, performance, and modern standards (Laravel 10/11+).

Coding & DevelopmentClaude

debug-nw

7754
from nativewind/nativewind

Debug a Nativewind v5 setup issue. Walks through common configuration problems with metro, babel, postcss, and dependencies.

Coding & Development

Go Production Engineering

3891
from openclaw/skills

You are a Go production engineering expert. Follow this system for every Go project — from architecture decisions through production deployment. Apply phases sequentially for new projects; use individual phases as needed for existing codebases.

Coding & Development

Database Engineering Mastery

3891
from openclaw/skills

> Complete database design, optimization, migration, and operations system. From schema design to production monitoring — covers PostgreSQL, MySQL, SQLite, and general SQL patterns.

Coding & Development

afrexai-code-reviewer

3891
from openclaw/skills

Enterprise-grade code review agent. Reviews PRs, diffs, or code files for security vulnerabilities, performance issues, error handling gaps, architecture smells, and test coverage. Works with any language, any repo, no dependencies required.

Coding & Development

API Documentation Generator

3891
from openclaw/skills

Generate production-ready API documentation from endpoint descriptions. Outputs OpenAPI 3.0, markdown reference docs, and SDK quickstart guides.

Coding & Development

bili-rs

3891
from openclaw/skills

Development skill for bili-rs, a Rust CLI tool for Bilibili (B站). Use when implementing features, fixing bugs, or extending the bilibili-cli-rust codebase. Provides architecture conventions, API endpoints, coding patterns, and project-specific constraints. Triggers on tasks involving adding CLI commands, calling Bilibili APIs, handling authentication, implementing output formatting, or working with the layered cli/commands/client/payloads architecture.

Coding & Development

Puppeteer

3891
from openclaw/skills

Automate Chrome and Chromium with Puppeteer for scraping, testing, screenshots, and browser workflows.

Coding & Development

pharaoh

3891
from openclaw/skills

Codebase knowledge graph with 23 development workflow skills. Query architecture, dependencies, blast radius, dead code, and test coverage via MCP. Requires GitHub App installation (read-only repo access) and OAuth authentication. Connects to external MCP server at mcp.pharaoh.so.

Coding & Development

git-commit-helper

3891
from openclaw/skills

Generate standardized git commit messages following Conventional Commits format. Use this skill when the user asks to commit code, write a commit message, or create a git commit. Enforces team conventions for type prefixes, scope naming, message length, and breaking change documentation.

Coding & Development

ask-claude

3891
from openclaw/skills

Delegate a task to Claude Code CLI and immediately report the result back in chat. Supports persistent sessions with full context memory. Safe execution: no data exfiltration, no external calls, file operations confined to workspace. Use when the user asks to run Claude, delegate a coding task, continue a previous Claude session, or any task benefiting from Claude Code's tools (file editing, code analysis, bash, etc.).

Coding & Development