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.

Blog site end result

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.

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.

  1. Execute the command below to create an Astro project called prepr-astro. Choose an Empty project and defaults for the remaining options.

    npm create astro@latest prepr-astro
  2. 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
  3. You should now be able to view your app on your localhost, for example, http://localhost:4321/.

  4. Open your Astro project with your preferred code editor.

  5. Go to the src/pages folder and update the index.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>
  6. Go to the src folder and create a layouts folder. In this folder, add the HTML components that can be reused by different pages to a file called Layout.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.

view component

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.

  1. Create a folder called lib in the src folder. Then, create a file called prepr.js in this folder. Copy the following code to this file to set up the endpoint:

    ./src/lib/prepr.js
    export 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
    }
  2. 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:

    ./.env
    PREPR_ENDPOINT=<YOUR-PREPR-API-URL>
  3. 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.

    access token

    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.

  4. 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.mjs
    import { 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

  1. Create a queries folder in the src folder that you just created and create a file named get-posts.js.

  2. Add the following query to this file to retrieve all blog posts:

    ./src/queries/get-posts.js
    const 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.

demo blog posts

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.

  1. Go to the src/pages folder and update the index.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.

blog post list

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.

  1. Create a file called get-post-by-slug.js in the queries folder and add the following query to this file to query a specific post by its slug:

    ./src/lib/queries/get-post-by-slug.js
    const 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.

  1. 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.

Blog post end result

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:

Last updated on

Was this article helpful?

We’d love to learn from your feedback