Astro > Astro + DatoCMS Overview

Astro + DatoCMS Overview

Astro is a modern static site generator and web framework that allows developers to build fast, content-focused websites using multiple frontend frameworks simultaneously. Its key differentiator is its "partial hydration" approach, which only sends JavaScript to the browser when necessary, resulting in extremely lightweight and fast-loading pages - making it particularly well-suited for content-heavy sites like blogs, documentation, and marketing pages where performance is crucial.

DatoCMS is the perfect companion to Astro.js since it offers content, images and videos on a globally-distributed CDN. With this combo, you can have an infinitely scalable website, ready to handle prime-time TV traffic spikes at a fraction of the regular cost.

In the next paragraphs, will see how easy it is to combine Astro with DatoCMS.

Fetching content from our GraphQL API

Let's start by installing @datocms/cda-client, a lightweight, TypeScript-ready package that offers various helpers around the native Fetch API to perform GraphQL requests towards DatoCMS Content Delivery API:

npm install --save @datocms/cda-client

We can now create a function we can use in all of our pages and components that need to fetch content from DatoCMS.

Create a new directory called lib, and inside of it, add a file called datocms.js:

import { executeQuery as libExecuteQuery } from "@datocms/cda-client";
import { DATOCMS_CDA_TOKEN } from "astro:env/server";
export async function executeQuery(query, options) {
return await libExecuteQuery(query, {
...options,
token: DATOCMS_CDA_TOKEN,
});
}

Make sure you set DATOCMS_CDA_TOKEN as an actual API token of your DatoCMS project. You can create a new one under "Settings > API Tokens".

We can now effortlessly build our first Astro page, using data from DatoCMS:

---
// src/pages/index.astro
const query = `
query HomeQuery {
blogPost { title }
}
`;
const data = await executeQuery(query);
---
<article>
<h1>{data.blogPost.title}</h1>
</article>

You can learn everything you need regarding how to build GraphQL queries on our Content Delivery API documentation.