Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created March 19, 2025 15:39
Show Gist options
  • Save tmcw/fd11d6859fdb8a52f99b3b07a69bb680 to your computer and use it in GitHub Desktop.
Save tmcw/fd11d6859fdb8a52f99b3b07a69bb680 to your computer and use it in GitHub Desktop.
import { getCollection } from "astro:content";
import type { APIRoute } from "astro";
export async function getStaticPaths() {
const docs = await getCollection("docs");
return docs.map((doc) => ({
params: { slug: doc.slug },
props: doc,
}));
}
export const GET: APIRoute = async ({ params }) => {
// If no slug is provided, return 404
if (!params.slug) {
return new Response("Not Found", { status: 404 });
}
try {
// Fetch all documentation
const docs = await getCollection("docs");
// Find the matching document
const doc = docs.find((d) => d.slug === params.slug);
if (!doc) {
return new Response("Document not found", { status: 404 });
}
// Return the raw document content (including frontmatter)
return new Response(doc.body, {
headers: {
"Content-Type": "text/markdown; charset=utf-8",
"X-Robots-Tag": "noindex, nofollow",
"Cache-Control": "public, max-age=3600",
},
});
} catch (error) {
console.error(`Error fetching markdown for slug "${params.slug}":`, error);
return new Response("Internal Server Error", { status: 500 });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment