Astro is a modern frontend framework that empowers developers to build fast and efficient static websites. With Astro, developers can leverage the power of modern JavaScript frameworks like React, Vue.js, and Svelte to create dynamic user interfaces while producing static HTML, CSS, and JavaScript files during the build process.

When coupled with WordPress as a headless content management system (CMS), Astro enables seamless integration of backend APIs and frontend code, allowing for efficient development of static websites with dynamic content. This approach offers several benefits.

Static sites generated with Astro and a WordPress backend boast superior performance. They can be served directly from a content delivery network (CDN), eliminating the need for server-side processing and resulting in faster load times and a smoother user experience.

This tutorial guides you through the process of setting up a static site using Astro hosted on Kinsta’s Static Site Hosting service and using WordPress for the backend.

The role of WordPress as a headless CMS

A headless CMS, like WordPress, separates the content management and delivery layers. It enables the backend to maintain content while a different system, like Astro, handles the frontend.

WordPress serves as a content repository, supplying data to the frontend, which displays the content to users via an API. This architecture enhances flexibility by enabling you to repurpose content for several outputs, giving WordPress users a familiar content management experience.

Decoupling the frontend from the backend also offers greater flexibility in frontend design and content migration. Additionally, enabling accessibility through APIs future-proofs the content.

Set up your development environment

There are three steps you must follow to set up your environment:

  1. Install Astro.
  2. Set up a WordPress site.
  3. Create a WordPress staging environment.

Prerequisites

To follow this tutorial, ensure you have the following:

Install Astro

  1. For your project, make a new directory and navigate into it.
  2. Scaffold a new project by running the command below in your terminal:
    npm create astro@latest

    This step produces configuration prompts. Set them up based on what you want.

    Terminal window providing instructions for configuring your new Astro project. The prompts are:- Where should we create your new project?- How would you like to start your new project?- Do you plan to write TypeScript?- How strict should TypeScript be?- Install dependencies?- Initialize a new git repository?
    Instructions for configuring your new Astro project.

  3. Once the project is successfully created, run npm run dev to launch the local development server on http://localhost:4321/.

    The Astro site Welcome page. providing links to documentation, integrations, themes, and community.
    Astro successfully installed.

Set up a WordPress site on Kinsta

Kinsta is a high-end WordPress hosting provider renowned for its intuitive interface and high-performance infrastructure. Follow these steps to create a WordPress site on Kinsta.

  1. On your MyKinsta dashboard, click WordPress Sites and then Create a site.
  2. Select the Install WordPress option and click Continue.
  3. Provide a Site name, select a Data center location, and click Continue.
  4. Provide all other information and click Continue.
  5. Once your site is created, you should see the message, “Your site has been created!”

Create a WordPress staging environment

Every WordPress installation at Kinsta has the option of establishing a free staging environment separate from the actual production site. This is great for testing new WordPress versions, plugins, code, and general development work.

The steps for creating a WordPress Staging environment on Kinsta are as follows.

  1. On the menu bar, click Live and then Create New Environment.

    Site Information page providing the data center location and site name.
    WordPress staging environment.

  2. Select Standard environment and click Continue.
  3. Click Clone an existing environment, provide an Environment name, select Live for Environment to clone, and click Continue.
  4. Once deployed, you can find the WordPress staging environment on the Live menu.

    Site Information page showing the Live menu with Live, Staging, and Create New Environment items
    Successful creation of a staging environment.

Integrate WordPress with Astro

Two primary methods exist for integrating WordPress with Astro: a REST API and GraphQL. This guide uses the GraphQL approach.

To integrate WordPress with Astro, you must:

  • Install WPGraphQL.
  • Connect Astro to WordPress.

Install WPGraphQL

First, install the WPGraphQL plugin on your WordPress site before using GraphQL to connect Astro to it.

  1. On the MyKinsta dashboard, select your WordPress site.
  2. On the menu bar, click Staging and then Open WP Admin in the upper-right corner.

    Site Information page showing the Staging menu and Push environment, Open WP Admin, and Visit site buttons
    Site Information page.

  3. Provide the credentials that you used when creating your WordPress site.
  4. Click the Plugins menu on the left navigation bar.
  5. Click Add New Plugin to add the WPGraphQL plugin.
  6. Search for “WPGraphQL,” click Install New to install the WPGraphQL plugin, and then click Activate.

    Add Plugins page showing the WPGraphQL plugin and others with an Install New button beside them
    Installing the WPGraphQL plugin.

  7. To test that the WPGraphQL plugin you installed works as expected, open the GraphQL menu on the navigation bar and click GraphiQL IDE.
  8. Use the following code in the GraphiQL IDE and click Run on the top left to execute the GraphQL query:
    {
      posts {
        nodes {
          slug
          excerpt
          title
        }
      }
    }

    This GraphQL query efficiently retrieves the slugs, excerpts, and titles of posts from the WordPress site.

    GraphQL page showing the GraphQL query code and a run button at the top
    Running the GraphQL query.

    On the left side of the GraphiQL IDE, you can see the list of posts returned by running the GraphQL query. Your WordPress GraphQL endpoint is accessible at https://your_wordpress_staging_url/graphql.

Connect Astro to WordPress

To connect Astro to WordPress, follow these instructions:

  1. Create a folder named graphql inside your Astro project’s src folder.
  2. Create a wordPressQuery.ts file inside the graphql folder.
  3. Use the following code inside your wordPressQuery.ts file. Make sure to replace https://your_wordpress_staging_url/graphql with your WordPress staging URL.
    interface gqlParams {
        query: String;
        variables?: object;
    }
    
    export async function wpquery({ query, variables = {} }: gqlParams) {
        const res = await fetch('https://your_wordpress_staging_url/graphql', {
            method: "post",
            headers: {
                "Content-Type": "application/json",
    
            },
    
            body: JSON.stringify({
                query,
                variables,
            }),
        });
    
        if (!res.ok) {
            console.error(res);
            return {};
        }
    
        const { data } = await res.json();
        return data;
    }

    This code defines an interface gqlParams and an asynchronous function wpquery that facilitates GraphQL queries to the WordPress site.

Develop your site with Astro and WordPress

  1. To create a new static page in Astro, create a file named blog.astro in the src/pages directory.
  2. Paste the following code in the newly created file:
    ---
    import Layout from "../layouts/Layout.astro";
    import { wpquery } from "../graphql/wordPressQuery";
    
    const data = await wpquery({
    	query: `
     	 {
    		posts{
    			nodes{
    				slug
    				excerpt
    				title
    			}
     		 }
    	 }  
     	`,
    });
    ---
    
    <Layout title="Astro-WordPress Blog Posts">
    	<main>
    		<h1><span class="text-gradient">Blog Posts</span></h1>
    
    		{
    			data.posts.nodes.map((post: any) => (
    				<>
    					<h2 set:html={post.title} />
    					<p set:html={post.excerpt} />
    				</>
    			))
    		}
    	</main>
    </Layout>
    <style>
    	main {
    		margin: auto;
    		padding: 1rem;
    		width: 800px;
    		max-width: calc(100% - 2rem);
    		color: white;
    		font-size: 20px;
    		line-height: 1.6;
    	}
    
    	h1 {
    		font-size: 4rem;
    		font-weight: 700;
    		line-height: 1;
    		text-align: center;
    		margin-bottom: 1em;
    	}
    </style>

    This code demonstrates how to use the wpquery function to fetch data from the WordPress site using GraphQL and render it on the Astro site.

  3. Use npm run dev to launch the local development server and see the latest WordPress blog posts on your Astro site at http://localhost:4321/blog.

    Astro project page displaying WordPress posts
    Astro project displaying WordPress posts.

To handle dynamic routing for individual blog posts, you need to use a combination of Astro’s dynamic routes and WordPress GraphQL’s query variables. By passing the post ID or slug as a query variable, you can dynamically generate the page content for each blog post. This allows for a more personalized user experience on your website.

Deploy your static site on Kinsta

Now, push your codes to your preferred Git provider (Bitbucket, GitHub, or GitLab). Next, follow these steps to deploy your static site to Kinsta:

  1. In the MyKinsta dashboard, click Static Sites and then Add site.
  2. Authorize Kinsta with your Git provider.
  3. Select a GitHub Repository and a Default branch. Provide a Display name for your static site and select the Automatic deployment on the commit box. This enables the automatic deployment of all new changes made to the repository. Click Continue.
  4. In the Build settings section, Kinsta automatically completes all the fields. Leave everything as is and click Create Site.
  5. Access your Astro site by going to the URL that appears as the domain on the Overview page of your deployed site. You can access blog posts via https://your_kinsta_site_url/blog.

Summary

There is more to what you can do with Astro and WordPress. The WordPress API can be used to access various data from your site and create unique use cases with Astro.

With Kinsta’s managed WordPress Hosting, you gain access to a robust infrastructure, worldwide CDN, edge caching, multiple data centers, and enterprise-level features. This ensures a fast and secure environment for your WordPress site.

Additionally, when you use frontend frameworks like Astro with headless WordPress, you can host its static files on Kinsta’s Static Site Hosting for free. This means you only pay for WordPress hosting, maximizing efficiency and cost-effectiveness.

What’s your take on headless WordPress and Astro? Have you explored their potential for creating unique solutions? Share your experiences in the comment section below.

Jeremy Holcombe Kinsta

Content & Marketing Editor at Kinsta, WordPress Web Developer, and Content Writer. Outside of all things WordPress, I enjoy the beach, golf, and movies. I also have tall people problems ;).