Headless WordPress is reworking how builders and companies use WordPress by decoupling content material administration from front-end growth.
In a Headless setup, WordPress acts purely as a CMS that exposes content material by way of an API, permitting you to decide on any front-end expertise to energy the user-facing web site or app.
Which means you possibly can construct a completely static frontend, use server-side rendering, or take a hybrid method—all utilizing a Headless setup. You can too use any framework or library that may fetch information from an exterior API, together with React, Vue, Astro, Subsequent.js, or a static web site generator.
Extra superior use circumstances of Headless WordPress embody ecommerce websites, SaaS functions, and cellular apps powered by WordPress. An instance you is perhaps conversant in is the Jetpack cellular app.
So how are you aware in case your challenge would profit from a Headless WordPress setup? And the way precisely do you join all of the items? Learn on:
Decoupled, however not disconnected: What’s Headless WordPress?
Earlier than we dig deeper, let’s take a look at how WordPress sometimes handles a request from a person:
In a conventional surroundings, WordPress handles your complete stack—content material administration and the presentation layer.
At a excessive degree, a typical request from a person could appear to be this:
- A person requests a web page in your web site.
- The request goes to WordPress by way of NGINX, the place we load
wp-config
, settings, plugins, and the energetic theme. - The requested web page/submit is decided, and information is queried from the database.
- From a template hierarchy, the precise templates are decided (
web page.php
,single.php
, and so forth.). - The template masses the header, content material, footer, and different mandatory components.
- WordPress outputs the HTML and sends it to the browser, the place it’s rendered for the person to see and work together with.
There are various similarities between a Headless web site and a daily web site. Nevertheless, for a Headless web site, your frontend must relay requests to WordPress’s REST API (or GraphQL) endpoint, and it’s as much as the frontend to assemble and serve the generated HTML.
For a Headless web site, a request would look extra like this:
- A person requests a web page in your web site.
- The front-end utility (e.g., Subsequent.js, Astro, or one other framework) could relay this request to WordPress by way of the REST API or the GraphQL endpoint. This can be pointless as a result of the HTML might already be generated if we’re doing a completely static construct or if the response is already cached.
- The request would go to WordPress, which has similarities to a extra conventional setup.
- WordPress will invoke the REST API Router (for REST), or WPGraphQL will parse the question.
- The database is queried.
- JSON is generated and returned to the front-end utility, which handles the JSON return information (e.g., updating the native state, re-rendering the DOM, and so forth.).
Headless refers to any WordPress construct during which WordPress acts because the content material layer whereas the frontend is served individually. There are various methods of doing this, and it’ll work in another way throughout completely different functions.
Some frontend functions will use server-side rendering (SSR), the place the markup is generated by way of a node server (and cached). Many frameworks have “adapters” for this, resembling Astro’s Cloudflare adapter, which abstracts the SSR logic away from you.
Some Headless websites are absolutely static, leveraging static web site technology (SSG), the place the WordPress backend is just used to generate the location’s HTML information. As soon as the location is constructed, the WordPress API is not wanted till the subsequent replace (like once you publish a brand new weblog submit or edit an current web page) triggers a rebuild. Which means each time you alter your web site or content material, the location should be rebuilt (both completely or partially by way of “partial SSG”).
When the location is stay, all of the HTML/markup is already constructed, and customers are being served these static HTML information.
The construct technique you select is dependent upon the challenge and what’s best to your use case. For instance, are you able to pre-render this web page forward of a person’s request? If that’s the case, SSG is probably going one of the best match.
That is additionally time to analysis the host the place you intend to host your front-end utility, overview their documentation, and see what adapters or workflows exist.
For instance, WordPress.com gives a managed, scalable, and safe WordPress surroundings for websites of any dimension. This eliminates lots of the infrastructure complications related to a self-hosted WordPress setup. You’ve got all of the options wanted for customized WordPress builds, figuring out the whole lot is dealt with.
Utilizing the Marketing strategy, you’ve got an ideal start line to your Headless construct with full entry to developer options like GitHub deployments, real-time backups, and SSH.
Utilizing GraphQL or the WordPress core REST API?
WordPress consists of a built-in REST API, which is extensively supported by third-party and group plugins. The API can also be utilized in WordPress core code and in Gutenberg.
The REST API permits customers (logged in and logged out) to carry out frequent CRUD operations on posts, pages, media, and different entities, relying on their entry degree.
In your front-end code base, you possibly can choose to make use of the REST API, or should you choose, you should use the WPGraphQL plugin, which lets you carry out the identical operations by way of GraphQL queries.
Many builders constructing Headless WordPress websites use GraphQL alongside fashionable frameworks like Astro, Subsequent.js, or Nuxt.
With GraphQL, we will request solely the fields we’d like and retrieve associated information by way of nested queries. For instance, we will use one question to fetch a submit and its writer with the identify and avatar picture URL:
The same name to /wp-json/wp/v2/posts?slug=hello-world
will give us many extra fields. As you possibly can see beneath, whereas the REST API does give us the writer ID, we can’t get the avatar URL by default from the identical request.
Alternatively, the WordPress REST API is supported out of the field, with no configuration wanted. This has led to a bigger ecosystem the place plugins present their endpoints by way of the WordPress REST API (one instance is WooCommerce).
I encourage you to take a look at each and see which can work higher to your challenge.
Who thrives with Headless WordPress?
Headless WordPress is commonly adopted by businesses and builders who need full management over a web site’s frontend. It makes use of the time-tested and securely managed backend of a managed WordPress host like WordPress.com.
Another use circumstances embody:
- Enterprises and high-traffic web sites: Headless WordPress is finest for organizations that want a scalable content material administration system with out the effort of server administration.
- Media and content-heavy platforms: Publishers who want quick, API-driven content material supply throughout a number of channels could go for a Headless WordPress setup.
- Ecommerce and SaaS functions: Companies integrating WordPress content material with customized storefronts, internet apps, or cellular apps could discover a Headless setup extra suited to their wants.
You may step by step undertake a Headless setup or combine it into your WordPress web site by interacting with the WordPress REST API from inside your theme.
Are there any drawbacks to picking a Headless setup?
After studying the above, it might appear that Headless WordPress is all the time the most suitable choice. Nevertheless, like anything, a Headless WordPress setup has advantages and disadvantages.
For a lot of initiatives, particularly should you’re not a developer, counting on WordPress for the entire stack makes extra sense. With this extra conventional WordPress setup, you continue to have quite a lot of methods of including interactivity by way of the block editor and the Interactivity API. Plus, the whole lot simply works utilizing a conventional WordPress setup as a result of the software program is so highly effective as-is.
A Headless setup comes with some potential drawbacks, together with:
- Extra upkeep work: Two separate codebases and applied sciences powering the front-end and back-end create complexities that you just don’t should cope with when utilizing a conventional WordPress setup.
- The vast number of themes, patterns, and design performance WordPress is understood for can be largely unavailable: You’ll be accountable for implementing a lot of this from scratch with code. How will you deal with weblog feedback? How about contact kinds? This performance is constructed into the WordPress software program to make it simpler for end-users to implement.
- Not all plugins help Headless setups: You could have to increase plugins or manually expose plugin information to the REST API or GraphQL.
- Managing two internet hosting environments: You’ll want one surroundings for the WordPress backend and one for the frontend. For a lot of websites, the frontend could be hosted as static information on the sting utilizing applied sciences like GitHub, AWS Cloudfront, Cloudflare, or a number of different static file hosts.
Issues to bear in mind earlier than choosing a Headless web site
Nonetheless unsure if a Headless WordPress setup is best for you? Contemplate the next:
- Customized code and experiences: A Headless construct requires developer time and technical selections tailor-made to your challenge. It is best to ask your self if the pliability of Headless structure is de facto mandatory to your challenge.
- Know-how familiarity: Are you or your workforce extra used to working with PHP or JavaScript?
- Your challenge’s targets: Whereas Headless websites supply extra flexibility and should improve efficiency (plus they’re distinctive, difficult, and enjoyable websites for builders to construct), these initiatives typically require elevated complexity and extra time spent on growth.
- WordPress’ under-the-hood tech: With out WordPress’ built-in caching and optimization options, you’ll must implement these your self utilizing a caching layer or service.
- Cache methods: With an optimized caching technique that integrates CDN edge servers with server-side caching—resembling Varnish, NGINX FastCGI cache, or a WordPress caching plugin—a WordPress web site could obtain efficiency ranges corresponding to a static web site.
- WordPress is Web optimization-friendly out of the field: With a Headless technique, you have to make sure that the front-end handles Web optimization correctly. This could contain SSR or SSG, which is already supported in frequent front-end frameworks. You’ll additionally must fetch Web optimization information from WordPress (resembling whether or not a web page ought to be listed, its Web optimization title, and its metadata). Redirects should even be appropriately dealt with, as you’ll lose the built-in WordPress permalink dealing with with a Headless setup.
- RSS feeds and sitemaps: With a Headless setup, this performance could should be coded and served from the frontend; it’s already supplied in WordPress core (and Jetpack should you’re internet hosting on WordPress.com).
Your Headless WordPress roadmap: Getting began
So Headless WordPress is correct to your challenge? Right here’s a fast getting began information that will help you out.
Getting ready the backend: Plugins and web site setup
The very first thing you want is a WordPress web site.
Tip: WordPress.com’s Marketing strategy or above gives a managed, scalable, and safe WordPress surroundings for websites of any dimension.
WordPress.com eliminates lots of the infrastructure complications related to a self-hosted setup. You’ve got all of the options wanted for customized WordPress builds, figuring out the whole lot behind the scenes is dealt with. Utilizing WordPress.com, you’ve got an ideal start line to your Headless construct with full entry to developer options like GitHub deployments, real-time backups, and SSH.
If you wish to simply check a number of issues and comply with together with this tutorial, you can even use WordPress.com’s free and open supply native growth surroundings, Studio, to spin up an area WordPress set up.
WordPress ships with a REST API, however as talked about above, many builders go for the WPGraphQL plugin when constructing Headless websites, which permits us so as to add a GraphQL endpoint to your WordPress web site.
For those who choose to make use of the REST API as a substitute, you can begin with out putting in any plugins.
Making a content material construction for API consumption
Let’s contemplate a WordPress submit or web page. We now have a title, an ID, a slug, a featured picture, and some extra fields. Nevertheless, most posts have wealthy content material added by way of the editor, which makes up many of the submit content material.
For that reason, the submit content material from the block editor could fluctuate considerably between posts.
Alternatively, content material like WooCommerce merchandise or a customized submit kind with customized fields (for instance, a submit kind outlined with Safe Customized Fields) could have many extra meta fields and little or no content material from the block editor.
Why does this matter? The structured meta fields, such because the submit title, are simpler to deal with when pulling content material from WordPress. We now have a fairly good concept of the way it will look and what information we’ll discover there.
The block editor content material, however, is a big string of textual content containing blocks and nested blocks. We now have much less management over this content material and may make fewer assumptions about its form.
The straightforward strategy to deal with block content material is to set it immediately as HTML in a div on the frontend. This provides you with the identical CSS lessons and markup because the WordPress submit, and you’ll type these in your front-end app or import the block types as a part of your construct course of.
One other method is to fetch the Gutenberg block markup, recursively parse the content material, and map the blocks to corresponding elements in your frontend. For instance, a Gutenberg block, like a picture, could be parsed to an equal .tsx
or .astro
part in your front-end code.
Whereas it offers you extra flexibility, it additionally means you have to write a brand new part for each block you intend to make use of.
That is additionally the place you must contemplate what information you want from WordPress. Some use circumstances could solely require fetching posts, whereas others want menus, Web optimization information, and person data.
Contact kinds or remark submissions might also should be returned to WordPress by way of REST requests except you intend to deal with them in another way.
Fetching information
In your WordPress web site’s dashboard, head to the WPGraphQL space. You’ll see the GraphQL IDE, which is the place you can begin interfacing with WordPress by way of GraphQL.
Tip: For those who’re unfamiliar with GraphQL, try the WPGraphQL docs.
It’s straightforward to construct complicated queries with clauses, pagination dealing with, and nested information whereas seeing the output immediately within the admin utilizing the IDE.
Constructing the frontend
As soon as we will fetch information from the backend, both by way of REST or GraphQL, we will begin translating this logic to our frontend.
Astro is an efficient choice, and I added some notes on the mixing beneath.
As a result of number of websites, use circumstances, and frameworks, that is certainly not an entire tutorial on construct a WordPress-powered Astro web site. Nonetheless, the steps are basic sufficient that they’ll apply to most related frontend frameworks and provide you with an concept of get began.
You can begin a brand new Astro challenge by working the next in your terminal:
npm create astro@newest -- --template weblog
This provides you with the newest model of Astro with prebuilt weblog templates. By default, this weblog is powered by Astro’s content material collections and can render markdown (and MDX) from .md
and .mdx
information saved within the frontend repository.
As well as, we’ll want a number of dependencies for interfacing with WordPress by way of GraphQL:
npm set up graphql-request graphql
Let’s begin our challenge to see what we’re working with by working npm run dev
. From the terminal output, we will see that the location runs on localhost:4321
.
Our present Astro web site renders content material from information within the src/pages
listing, the place the [...slug].astro
is dynamic and accountable for parsing and rendering the markdown information contained in the src/content material/weblog
listing.
Since we’ll get our content material from WordPress, we will take away the src/content material
listing and the content material.config.ts
file.
In src/constants.ts
, outline a brand new fixed to your web site’s WPGraphQL endpoint. Reminder: This could be a stay web site or an area Studio web site.
// Place any world information on this file.
// You may import this information from wherever in your web site by utilizing the `import` key phrase.
export const SITE_TITLE = 'Astro Weblog';
export const SITE_DESCRIPTION = 'Welcome to my web site!';
export const WORDPRESS_API_URL = 'https://astroheadlessbuild.wpcomstaging.com/graphql';
We already know we have to get all posts, the slugs, and a single submit given a slug. As we progress, extra queries will possible be required. Class, tag, and writer pages already come to thoughts.
We are able to create a brand new file at src/lib/graphql.ts
.
Any question you want could be added and exported from this file. The IDE contained in the WPGraphQL admin web page is a superb place to experiment and write new queries. Let’s add one to fetch all our posts for now:
import { GraphQLClient } from 'graphql-request';
import { WORDPRESS_API_URL } from '../consts';
// Create a GraphQL shopper occasion
export const graphQLClient = new GraphQLClient(WORDPRESS_API_URL);
// Question to get a listing of posts
export const GET_POSTS = `
question GetPosts($first: Int, $after: String) {
posts(first: $first, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
slug
title
date
excerpt
featuredImage {
node {
sourceUrl
altText
}
}
}
}
}
`;
Utilizing the fetched information in our frontend
In Astro, we’re choosing a static construct. Due to this, we should inform it which pages to construct for us.
We are able to modify the [...slug].astro
file with getStaticPaths
, permitting Astro to know all of the attainable URLs/paths at construct time.
It additionally permits us to make use of the info immediately within the template:
import { graphQLClient, GET_POSTS } from '../../lib/graphql';
import kind { WordPressPostsResponse, WordPressTerm } from '../../lib/varieties';
import BlogPost from '../../layouts/BlogPost.astro';
import { formatDate } from '../../lib/utils';
export async operate getStaticPaths() {
const allPaths = [];
let afterCursor = null;
let hasNextPage = true;
whereas (hasNextPage) {
const response: WordPressPostsResponse = await graphQLClient.request<WordPressPostsResponse>(GET_POSTS, {
first: 10, // Fetch in batches of 10
after: afterCursor,
});
allPaths.push(
...response.posts.nodes.map(submit => ({
params: { slug: submit.slug },
props: { submit },
}))
);
hasNextPage = response.posts.pageInfo.hasNextPage;
afterCursor = response.posts.pageInfo.endCursor;
}
return allPaths; // Return an array as required by Astro
}
const { submit } = Astro.props;
if (!submit) {
return Astro.redirect('/404');
}
// Format the submit information to match the BlogPost part props
const postData = undefined,
;
// Get the submit content material
const content material = submit.content material || '';
// Get extra submit metadata
const writer = submit.writer?.node;
const classes = submit.classes?.nodes || [];
const tags = submit.tags?.nodes || [];
We are able to now run npm run construct && npm run preview
, which can convert all our static paths (e.g., weblog posts) into HTML information and serve the static information from an area dev server:
Last ideas: Going Headless with WordPress
On this submit, we’ve coated the professionals and cons of Headless WordPress, fetch information from our WordPress.com backend, and how one can shortly get began with a brand new Headless frontend in Astro.
Though my instance is a quite simple web site, WordPress.com presents a sturdy, low-maintenance backend for Headless websites of any dimension, whether or not it’s an ecommerce web site, an app, or a content-heavy web site.
Our managed infrastructure, safety, and API-first capabilities make WordPress.com a wonderful alternative for companies and builders seeking to scale.
Subscribe to MarketingSolution.
Receive web development discounts & web design tutorials.
Now! Lets GROW Together!