Astro Quick start guide
Estimated duration: 10 minutes
This guide shows you how to connect Prepr to an Astro project to get data from Prepr CMS. You'll learn how to make a simple blog with Astro and Prepr CMS. By the end of this guide, you'll have a working app that looks like the image below.
If you want to skip ahead, try out the zero installation demo on Stackblitz (opens in a new tab) or clone the repository on GitHub (opens in a new tab) to run the demo locally.
Prerequisites
You need to have the following setup before you connect your Astro project to Prepr.
- A free Prepr account (opens in a new tab)
- An environment with demo data in Prepr
- The latest version of Node.js (opens in a new tab)
Create a simple Blog website with Astro and Prepr CMS
Create a new Astro project
The instructions below will guide you on how to create an empty Astro project for your blog app.
If you have an existing Astro project, then you can skip this step.
-
Execute the command below to create an Astro project called
prepr-astro
. Choose anEmpty
project and defaults for the remaining options.npm create astro@latest prepr-astro
-
When the project is successfully created, go to the
prepr-astro
folder, the root directory of the project, and execute the commands below to start the project.cd prepr-astro
npm run dev
-
You should now be able to view your app on your localhost, for example,
http://localhost:4321/
. -
Open your Astro project with your preferred code editor.
-
Go to the
src/pages
folder and update theindex.astro
file with the following code to display your blog:./src/pages/index.astro--- import Layout from '../layouts/Layout.astro'; --- <Layout title="My blog site"> <h1> My blog site </h1> </Layout>
-
Go to the
src
folder and create alayouts
folder. In this folder, add the HTML components that can be reused by different pages to a file calledLayout.astro
with the following code:./src/layouts/Layout.astro--- export interface Props { title: string; } const { title } = Astro.props; --- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="description" content="Astro description"> <meta name="viewport" content="width=device-width" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <meta name="generator" content={Astro.generator} /> <title>{title}</title> </head> <body> <slot /> </body> </html>
You should now see something like the image below on your localhost.
Connect to Prepr
Set up a connection to Prepr to retrieve CMS data with GraphQL. The instructions below show you how to connect to Prepr directly from your project so that you can execute GraphQL queries to request data from the Prepr API.
-
Create a folder called
lib
in thesrc
folder. Then, create a file calledprepr.js
in this folder. Copy the following code to this file to set up the endpoint:./src/lib/prepr.jsexport async function Prepr(query, variables) { const response = await fetch(import.meta.env.PREPR_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query, variables }), }) return response }
-
We recommend using environment variables to store sensitive information like access tokens. To add environment variables, create a
.env
file in the root directory of your project and add the API URL as follows:./.envPREPR_ENDPOINT=<YOUR-PREPR-API-URL>
-
Replace the placeholder value
<YOUR-PREPR-API-URL>
with the API URL of an access token from Prepr. Get this URL by logging into your Prepr account:
a. Go to Settings → Access tokens to view all the access tokens.
b. Copy the API URL value from the GraphQL Production access token to only retrieve published content items.Use the GraphQL Production API URL to request published content items for your live app and use the GraphQL Preview value to make a preview of unpublished content items for your content editors.
-
Update the astro config file
astro.config.mjs
with the code below to use server-side rendering. Check out the Rendering strategies docs for more details../astro.config.mjsimport { defineConfig } from 'astro/config'; // https://astro.build/config export default defineConfig({ // Set up SSR output: 'server' });
If your app runs without errors, then the setup above was done correctly. The next step is to fetch content from Prepr using the endpoint that you set up.
Fetch multiple blog posts
Now that your app is connected to Prepr, fetch the blog posts from Prepr.
Add a GraphQL query
-
Create a
queries
folder in thesrc
folder that you just created and create a file namedget-posts.js
. -
Add the following query to this file to retrieve all blog posts:
./src/queries/get-posts.jsconst GetPosts = ` query { Posts { items { _id _slug title } } } ` export default GetPosts
You can create and test GraphQL queries using the Apollo explorer (opens in a new tab) from Prepr. Open the API Explorer from the Post content item page in Prepr or the access token page.
If you’re using preloaded demo data in your Prepr CMS environment, as mentioned above in the Prerequisites section, you should have a few published blog posts as shown in the below image. The query will retrieve the ID, Slug, and Title of each blog post.
In the next step, we'll fetch and process the query response.
Fetch data
Now that the query has been added, fetch the blog posts from Prepr and display them in the app.
-
Go to the
src/pages
folder and update theindex.astro
file to execute the query and display the list of blog posts:./src/pages/index.astro--- import Layout from '../layouts/Layout.astro'; import {Prepr} from '../lib/prepr.js'; import GetPosts from '../queries/get-posts.js'; const response = await Prepr(GetPosts) const { data } = await response.json() const posts = data.Posts --- <Layout title="Welcome to Astro."> <h1> My blog site </h1> <ul> { posts.items.map((post) => ( <li> <a href={post._slug}>{post.title}</a> </li> )) } </ul> </Layout>
Now when you view the website on your localhost, you'll see something like the image below.
Fetch individual blog posts
Now you have the list of blog posts with links to them. When a visitor clicks a blog post link, your app should open a detailed post page automatically.
However, we haven't created the detailed page yet. Now, when you click the link, an empty page opens with the slug in the URL.
The instructions below show you how to fetch the blog post details based on the slug of the post that was clicked.
-
Create a file called
get-post-by-slug.js
in thequeries
folder and add the following query to this file to query a specific post by its slug:./src/lib/queries/get-post-by-slug.jsconst GetPostBySlug = ` query ($slug: String) { Post (slug: $slug) { _id title cover { url(width: 300, height: 250) } content { __typename ... on Text { _id body text } ... on Assets { items { _id url(width: 300, height: 250) } } } } } ` export default GetPostBySlug
Now that the query is added, fetch the individual blog post by its slug. Fetch the post title, cover image and the blog post content.
The Post content is stored in a Dynamic content field. Check out the GraphQL docs for more details on how to fetch the data within this field.
-
Go to the
src/pages
folder and create a file called[...slug].astro
file with the following code to execute the query that you just created and display the retrieved blog post:./src/pages/[...slug].astro--- import Layout from '../layouts/Layout.astro'; import {Prepr} from '../lib/prepr.js'; import GetPostBySlug from '../queries/get-post-by-slug.js'; const { slug } = Astro.params; const response = await Prepr(GetPostBySlug, {slug}) const { data } = await response.json() const post = data.Post --- <Layout title={post.title}> <main> <h1>{post.title}</h1> <div class="my-10"> <img src={post.cover.url} /> </div> { post.content.map((content) => ( <div> { content.__typename === "Assets" && <img src={content.items[0].url} /> } { content.__typename === 'Text' && <div set:html={content.body}></div> } </div> )) } </main> </Layout>
Now, when you view your site, you can click a blog post to open a specific post like in the image below.
All done
Congratulations! You have successfully connected an Astro project to Prepr for a simple Blog app.
Next steps
To learn more on how to expand your project, check out the following resources:
- Draft more queries for components and other field types
- How to install and use Tailwind (opens in a new tab)
- Deploy your Astro app with Vercel (opens in a new tab)
Was this article helpful?
We’d love to learn from your feedback