Astro is a content-focused web framework that renders HTML at build time (SSG) or per-request (SSR). The key UUID rule in Astro: all ID generation must happen on the server, never in client-rendered components. Astro’s server-side rendering model makes this natural — API endpoints, actions, and server component frontmatter all run in Node.js where crypto.getRandomValues() is available. See UUID in React and Next.js for the hydration mismatch context.
API endpoint with UUID v7
// src/pages/api/orders.ts
import type { APIRoute } from 'astro';
import { v7 as uuidv7 } from 'uuid';
import { db } from '../../db';
export const POST: APIRoute = async ({ request }) => {
const body = await request.json();
const order = {
id: uuidv7(), // server-side — safe
customerId: body.customerId,
total: body.total,
};
await db.insert(orders).values(order);
return new Response(JSON.stringify(order), {
status: 201,
headers: { 'Content-Type': 'application/json' },
});
};
Server-rendered component with UUID v7
---
// src/pages/orders/new.astro
// This frontmatter runs on the server — UUID v7 is safe here
import { v7 as uuidv7 } from 'uuid';
import { db } from '../../db';
let result = null;
if (Astro.request.method === 'POST') {
const data = await Astro.request.formData();
const order = {
id: uuidv7(),
customerId: data.get('customerId') as string,
total: Number(data.get('total')),
};
await db.insert(orders).values(order);
result = order;
}
---
<form method="POST">
<input name="customerId" required />
<input name="total" type="number" required />
<button>Create Order</button>
</form>
{result && <p>Created order {result.id}</p>}
Astro Actions (Astro 4.15+) with UUID v7
// src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro:schema';
import { v7 as uuidv7 } from 'uuid';
export const server = {
createOrder: defineAction({
input: z.object({
customerId: z.string(),
total: z.number().positive(),
}),
handler: async ({ customerId, total }) => {
const order = { id: uuidv7(), customerId, total };
await db.insert(orders).values(order);
return order;
},
}),
};
---
// src/pages/orders.astro
import { actions } from 'astro:actions';
---
<form method="POST" action={actions.createOrder}>
<input name="customerId" required />
<input name="total" type="number" required />
<button>Create Order</button>
</form>
Astro Actions run on the server — UUID v7 generation is safe, and the generated ID is available in the response for client-side use. See UUID in JavaScript.
Content collection with UUID v7 IDs
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
const products = defineCollection({
type: 'content',
schema: z.object({
id: z.string().uuid(), // UUID v7 in frontmatter
title: z.string(),
price: z.number(),
}),
});
export const collections = { products };
---
# src/content/products/widget.md
id: "018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f" # UUID v7
title: "Widget Pro"
price: 49.99
---
Idempotency in API endpoints
// src/pages/api/payments.ts
import type { APIRoute } from 'astro';
import { validate } from 'uuid';
export const POST: APIRoute = async ({ request }) => {
const idempotencyKey = request.headers.get('idempotency-key');
if (!idempotencyKey || !validate(idempotencyKey)) {
return new Response('Valid UUID Idempotency-Key required', { status: 400 });
}
// Check cache, process, store result...
};
Further reading
- UUID in React and Next.js — hydration patterns
- UUID as Idempotency Keys
- UUID in JavaScript — full guide
- UUID Generation Strategies — client vs server
External references
Frequently asked questions
Can I generate UUID v7 in an Astro component?
Only in server-rendered (output: 'server') or hybrid components. In a .astro component's frontmatter (the --- block), code runs at request time on the server, so v7() from the uuid package is safe. Never generate UUIDs in client-side <script> tags or in framework components (React/Vue/Svelte) that hydrate on the client — this causes hydration mismatches. See UUID in React and Next.js.
How do I use UUID v7 in an Astro API endpoint?
Astro API endpoints (src/pages/api/**.ts) run on the server. Import v7 as uuidv7 from the uuid package and generate IDs in the POST handler. The uuid package is a standard Node.js dependency — no special Astro configuration needed.
Does Astro content collections support UUID v7 slugs?
Astro content collection entries use file-based slugs by default. You can define a custom id field in the collection schema using z.string().uuid() and set it in the frontmatter to a UUID v7 value. This is useful for content that needs a stable, globally unique identifier independent of the file path.