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:
- Install Astro.
- Set up a WordPress site.
- Create a WordPress staging environment.
Prerequisites
To follow this tutorial, ensure you have the following:
- Fundamental understanding of HTML, CSS, and JavaScript
- Node.js and npm (Node Package Manager) or yarn installed on your computer
- A Kinsta account. Sign up to host a static site for free and access the MyKinsta dashboard.
Install Astro
- For your project, make a new directory and navigate into it.
- 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.
- Once the project is successfully created, run
npm run dev
to launch the local development server on http://localhost:4321/.
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.
- On your MyKinsta dashboard, click WordPress Sites and then Create a site.
- Select the Install WordPress option and click Continue.
- Provide a Site name, select a Data center location, and click Continue.
- Provide all other information and click Continue.
- 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.
- On the menu bar, click Live and then Create New Environment.
- Select Standard environment and click Continue.
- Click Clone an existing environment, provide an Environment name, select Live for Environment to clone, and click Continue.
- Once deployed, you can find the WordPress staging environment on the Live menu.
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.
- On the MyKinsta dashboard, select your WordPress site.
- On the menu bar, click Staging and then Open WP Admin in the upper-right corner.
- Provide the credentials that you used when creating your WordPress site.
- Click the Plugins menu on the left navigation bar.
- Click Add New Plugin to add the WPGraphQL plugin.
- Search for “WPGraphQL,” click Install New to install the WPGraphQL plugin, and then click Activate.
- To test that the WPGraphQL plugin you installed works as expected, open the GraphQL menu on the navigation bar and click GraphiQL IDE.
- 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
, andtitles
of posts from the WordPress site.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:
- Create a folder named graphql inside your Astro project’s src folder.
- Create a wordPressQuery.ts file inside the graphql folder.
- 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 functionwpquery
that facilitates GraphQL queries to the WordPress site.
Develop your site with Astro and WordPress
- To create a new static page in Astro, create a file named blog.astro in the src/pages directory.
- 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. - Use
npm run dev
to launch the local development server and see the latest WordPress blog posts on your Astro site athttp://localhost:4321/blog
.
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:
- In the MyKinsta dashboard, click Static Sites and then Add site.
- Authorize Kinsta with your Git provider.
- 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.
- In the Build settings section, Kinsta automatically completes all the fields. Leave everything as is and click Create Site.
- 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.
Leave a Reply