guide astrowebdev

Getting started with Astro

A quick reference for the Astro things I always look up.

Content collections

Define schemas in src/content.config.ts using the Content Layer API:

import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';

const blog = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
  schema: z.object({
    title: z.string(),
    publishDate: z.coerce.date(),
  }),
});

Rendering a collection entry

---
import { getCollection, render } from 'astro:content';

const posts = await getCollection('blog');
const post = posts[0];
const { Content, headings } = await render(post);
---

<Content />

Hybrid SSR

Add export const prerender = false to any page or API route to opt into server rendering:

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  // ...
};