stnd.build

Business Logic in Astro Component

Error: [ERR_ASTRO_BUSINESS_LOGIC] Found direct database query or business mutation in .astro frontmatter. Law #3: .astro files must hold no business logic.


The Problem

An .astro component’s frontmatter contains direct database queries, SQL execution, third-party API mutations (like Stripe or billing), or complex algorithmic orchestration.

---
// Problematic: Direct database access in .astro frontmatter
import { db } from "../db.js";

const users = await db.selectFrom("users").selectAll().execute();
await stripe.customers.create({ email: Astro.request.headers.get("x-user") });
---

The Why

Astro components are presentation templates designed to render HTML, CSS, and inject client components.

  1. Separation of Concerns (Law #3): Presentation should never be coupled to database schema or external transactional APIs.
  2. Reusability & Testability: When business logic lives inside .astro files, it cannot be unit tested without mounting the full Astro compiler environment, and cannot be reused in API endpoints, CLI scripts, or background workers.
  3. Edge & SSR Portability: Business models in Standard live in modules/core/models/ or module actions/, making them agnostic to the rendering layer.

The Solution

Move all data queries and mutations into designated domain models or action files:

1. Read Queries $\longrightarrow$ Domain Models

Encapsulate database reads and business queries in modules/core/models/ or modules/<feature>/models/:

// modules/core/models/User.ts
export async function getActiveUsers() {
  return await db.selectFrom("users").selectAll().execute();
}

Then simply invoke the domain model in .astro:

---
// Compliant: Presentation only
import { getActiveUsers } from "@modules/core/models/User.js";

const users = await getActiveUsers();
---
<UserList users={users} />

2. Mutations & Side Effects $\longrightarrow$ Actions

Handle state mutations, API calls, and transaction orchestration in module actions/:

// modules/billing/actions/subscribe.ts
export async function createCustomer(email: string) {
  return await stripe.customers.create({ email });
}