Headless Drupal with React: Complete Guide for Modern Web Development

headless drupal with react

As the demands for flexibility, scalability, and performance rise, traditional content management systems (CMS) often fall short. That’s where the concept of “headless CMS” comes into play.

When headless Drupal is used with React you can separate the frontend layer from the backend content management. That provides web developers a space for building frontend and backend independently.

To help you learn how, we’ll first understand both the technologies diving into working and features. Then we’ll guide you through the complete process of integrating headless Drupal with React. With that, let’s begin!

What is Headless Drupal?

Headless Drupal is a decoupled approach to Drupal where the frontend (user interface) is separated from the backend (content management system). In a traditional CMS setup, Drupal handles both the backend and the frontend.

However, in a headless setup, Drupal only takes care of the backend and the frontend is managed by a separate web development technology. The frontend framework could be JavaScript frameworks like React, Angular, or Vue.js. This separation allows for greater flexibility and scalability in building websites and applications.

How Does Headless Drupal Work?

To know how to use headless Drupal with React, you need to understand how it works. Here is the working of headless Drupal:

1. Content Creation: Content editors use Drupal’s admin interface to create and manage content. This part remains largely unchanged from a traditional Drupal setup.

2. Content Storage: The content is stored in Drupal’s database, just like in a traditional CMS setup.

3. API Layer: Drupal exposes the content through APIs (JSON, REST, GraphQL). These APIs are responsible for providing the content to the frontend applications.

4. Frontend Application: A separate frontend application, built using frameworks like React, fetches the content from Drupal’s API endpoints and displays it to users. This application can be hosted separately and interact with Drupal purely through HTTP requests.

This working of headless Drupal allows web developers to build dynamic interfaces and robust functionality.

What is React?

React is a popular open-source JavaScript library used for building user interfaces, especially for single-page applications (SPAs). It lets you build complex UIs from smaller, reusable pieces called components. Using its state management system, you can manage components and handle dynamic data.

It focuses on the view layer of the Model-View-Controller (MVC) architecture that handles the view logic of the frontend. React was developed and is maintained by Facebook, along with a community of individual developers and companies.

Key Features of React

React offers a robust set of features that make it a popular choice for building sites with interactive frontend. Here are some of its key features:

  • Component-Based Architecture: React structures applications using components, which are self-contained and reusable pieces of UI. This approach simplifies development and maintenance, as components can be combined to build complex UIs.
  • Declarative UI: With React’s declarative style, developers define what the UI should look like for different website states. React automatically manages the rendering process, ensuring that the UI stays in sync with the application state.
  • Virtual DOM: It uses a Virtual DOM to efficiently manage updates to the actual DOM. Changes are first made in the virtual representation, and only the necessary updates are applied to the real DOM, optimizing performance.
  • JSX (JavaScript XML): JSX is a syntax extension that allows developers to write HTML-like code directly in JavaScript. It simplifies component creation by combining UI design and logic, making the code more readable and easier to write.
  • Unidirectional Data Flow: Data in React flows in one direction—from parent to child components—through props. This predictable data flow makes it easier to manage and debug the application’s state.
  • State Management: React components can maintain their own state, which is used to store data that may change over time. It re-renders the component automatically when the state changes, keeping the UI updated.
  • React Hooks: Hooks are functions that let developers use state and other React features in functional components. Hooks like useState and useEffect provide powerful ways to manage state and lifecycle events without writing class components.
  • React Router: It is a popular library used to manage routing in React applications. React Router enables navigation between different views, facilitating the creation of single-page applications (SPAs) that handle routing dynamically.
  • React Native: It allows developers to use React for building mobile applications. React Native leverages React’s component-based architecture to create native mobile apps for iOS and Android using a shared codebase.

These features make the frontend development easy and efficient. Using React allows developers to build mobile friendly sites with native development features. That is one of the reasons why web development experts prefer to build interactive and functional websites.

Struggling to leverage the power of headless Drupal?

Why Use Headless Drupal with React?

The combination of Headless Drupal and React offers a powerful and flexible solution for building modern web applications. Here are key reasons why developers might choose this architecture:

  • Flexibility: Headless Drupal separates the frontend from the backend, allowing developers to choose React or any other frontend technology to build the UI. This decoupling provides greater flexibility in designing and makes it easier to implement changes without affecting the backend system.
  • Performance: By using React, which utilizes a Virtual DOM, developers can achieve faster and more efficient UI updates. React’s component-based rendering and its efficient handling of state changes lead to quicker page loads, enhancing overall performance.
  • User Experience: Features of React, such as smooth transitions, real-time updates, and responsive designs, are easier to implement with React. That leads to a more interactive and  improved user experience.
  • Scalability: Headless Drupal with React is well-suited for large-scale applications. Drupal handles complex content models, workflows, and permissions on the backend. Conversely React efficiently manages the rendering and state on the frontend. This separation allows each layer to build independently for higher scalability.
  • Reusability: React’s component-based architecture allows developers to create reusable components. This reusability speeds up the web development process, ensures consistency, and reduces the amount of code that needs to be written.
  • API-First Approach: Headless Drupal reveals content through APIs, enabling a consistent and centralized content delivery mechanism. React can retrieve these APIs to fetch and display content, ensuring that data is consistent across different platforms and devices.
  • Multi-Channel Content Delivery: Headless Drupal with React supports delivering content across channels, such as web and IoT devices. Developers can use a  single backend to manage content and APIs. That lets them ensure consistent content delivery across various platforms.

These strengths of both Headless Drupal and React allows professional web development services to build fast, scalable, and secure applications. Using these combinations would be ideal for projects requiring complex content management with a dynamic frontend. Now, let’s find out how to use both of them together for your project.

How to Use Headless Drupal with React?

Using Headless Drupal with React involves setting up Drupal as the backend to manage content and React as the frontend to present the content. Here’s a step-by-step guide on how to integrate Headless Drupal with React:

Prerequisites

To set up Headless Drupal with React, you need:

  • A basic understanding of Drupal and React.
  • A working installation of Drupal with the JSON module enabled.
  • A React development environment is set up using tools like create-react-app.
  • Familiarity with making HTTP requests and handling APIs in React using libraries like Axios or Fetch API.

Once you have these prerequisites, we can begin the setup process.

1. Set Up Drupal as a Headless CMS

To start using Drupal as a headless CMS, you need to install and configure it to handle content management and expose data via APIs. This involves setting up Drupal, enabling essential modules, and configuring content types.

Step 1: Begin by installing Drupal. Download it from the official Drupal website and follow the installation guide to set up the backend.

Step 2: Enable and activate the required modules like JSON to expose Drupal content as JSON. To do so, go to Extend in the Drupal admin panel, search for JSON:API, and enable it. This module will allow you to access Drupal content through API endpoints.

Step 3: Set up your content types in Drupal. These could include articles, pages, or custom content types. Define the necessary fields and configure their settings according to your content needs.

In this step, we installed Drupal and configured it with modules like JSON:API to expose content as JSON. Content types and fields were defined to structure the content.

2. Expose Drupal Data via JSON

This step involves making Drupal’s content accessible through API endpoints using the JSON module. Here, we’ll expose content in a format that React can consume, facilitating data exchange between the backend and frontend.

Step 1: Once the JSON:API module is enabled, Drupal automatically creates endpoints for each content type. For example, accessing https://your-drupal-site.com/jsonapi/node/article will provide a JSON representation of all article nodes.

Step 2: If needed, you can customize the JSON responses using additional modules like REST UI or GraphQL. These modules offer more control over what data is exposed and how it is structured.

Step 3: Use Views for custom data endpoints if needed. Go to Structure > Views and add a new view with REST export.

With JSON enabled, you can access Drupal content via predefined endpoints. That allows you to fetch data from Drupal and use it in your React application.

3. Setting Up a React Project

Setting up a React project involves creating a new React application and installing the necessary dependencies. This environment will serve as the frontend where you’ll build user interfaces and handle interactions with the Drupal backend.

Step 1: Create a React App using create-react-app to initialize your React project:

npx create-react-app my-headless-drupal-app
cd my-headless-drupal-app

Step 2: Install Axios to handle API requests:

npm install axios

Step 3: Set up environment variables for your Drupal API endpoint. Create a .env file in your React project root:

REACT_APP_DRUPAL_API=https://your-drupal-site/jsonapi

Here we created a new React project using create-react-app, and the necessary dependencies, like axios, were installed.

4. Fetching Data from Drupal in React

In this step, you’ll create a service in React to fetch data from Drupal’s API. This involves writing functions to handle API requests and retrieve content from your Drupal backend for use in your React components. Here is a sample code to create an API service in React:

// src/api/drupalApi.js
import axios from 'axios';
const API_BASE_URL = process.env.REACT_APP_DRUPAL_API;
export const fetchArticles = async () => {
    try {
        const response = await axios.get(`${API_BASE_URL}/node/article`);
        return response.data;
    } catch (error) {
        console.error('Error fetching articles:', error);
        throw error;
    }
};

Here, axios was used to make GET requests to the Drupal endpoints, and the retrieved JSON data was stored in React’s state.

5. Displaying Drupal Content in React Components

After fetching data, you’ll display it in React components. This step involves creating components that render content fetched from Drupal, ensuring that the data is presented in a user-friendly format.

Step 1: Use the fetchArticles function in your React components to retrieve and display data from Drupal. Here is how you can write API service in your React components:

// src/components/ArticlesList.js
import React, { useEffect, useState } from 'react';
import { fetchArticles } from '../api/drupalApi';
const ArticlesList = () => {
    const [articles, setArticles] = useState([]);
    useEffect(() => {
        const getArticles = async () => {
            const data = await fetchArticles();
            setArticles(data.data);
        };
        getArticles();
    }, []);
    return (
        <div>
            <h1>Articles</h1>
            <ul>
                {articles.map((article) => (
                    <li key={article.id}>{article.attributes.title}</li>
                ))}
            </ul>
        </div>
    );
};
export default ArticlesList;

Step 2: Use JavaScript’s map() function to iterate over the data and render it within the React components:

const ArticleList = ({ articles }) => (
    <div>
        {articles.map(article => (
            <div key={article.id}>
                <h2>{article.attributes.title}</h2>
                <p>{article.attributes.body.value}</p>
            </div>
        ))}
    </div>
);

Here, we created React components and mapped them to display the content dynamically based on the data stored in the state.

6. Implementing Routing in React

Integrate a library like React Router to manage navigation within your React application. This allows users to navigate between different sections and dynamically update content based on their location.

Step 1: To handle navigation within your React application, install React Router:

npm install react-router-dom

Step 2: Create routes in your React app to navigate between different components or views:

// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ArticlesList from './components/ArticlesList';
import ArticleDetail from './components/ArticleDetail'; // Assume you have a detailed view
const App = () => {
    return (
        <Router>
            <Switch>
                <Route path="/" exact component={ArticlesList} />
                <Route path="/article/:id" component={ArticleDetail} />
            </Switch>
        </Router>
    );
};
export default App;

Installing and configuring React Router lets it handle navigation in your website. Plus, setting up routes to different components, enabling users to move seamlessly through the site.

7. Handling Authentication and Permissions

If your Drupal content requires authentication, configure token-based authentication or OAuth 2.0 in Drupal.

Step 1: Here is how you can install and configure OAuth module to manage user access:

composer require drupal/simple_oauth
drush en simple_oauth -y

To configure OAuth settings in Drupal admin, navigate to Configuration > People > Simple OAuth.

Step 2: Use Axios or Fetch API to include authentication tokens in your requests. Update your api.js to handle token-based authentication:

import axios from 'axios';
const API_BASE_URL = 'http://your-drupal-site.com/jsonapi';
const AUTH_TOKEN = 'your-auth-token'; // Replace with actual token retrieval logic
export const fetchArticles = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/node/article`, {
      headers: { 'Authorization': `Bearer ${AUTH_TOKEN}` }
    });
    return response.data;
  } catch (error) {
    console.error("Error fetching articles:", error);
    throw error;
  }
};

This step involved securing the site by setting up authentication in both Drupal and React to manage access to sensitive data.

8. Adding Interactivity and Performance

To make the site more engaging, add interactivity and optimize user experience. This involves implementing dynamic features and improving the overall responsiveness of the application.

Step 1: Use React’s Context API or a state management library like Redux to manage the application’s state, especially as it grows in complexity.

Step 2: Consider using libraries like Material-UI or Bootstrap for modern UI components. These libraries provide ready-to-use components that can enhance the look and feel of your site.

Step 3: Optimize performance by implementing techniques like code splitting, lazy loading of components, and efficient data fetching strategies. Tools like React’s Suspense and React.lazy can help with this.

Adding interactivity and enhancing performance will provide better responsiveness and user experience.

By integrating Headless Drupal with React, you leverage Drupal’s powerful CMS and React’s dynamic frontend capabilities. The setup requires expertise in various development technologies which could be complex. So, it’s recommended to contact our web development company to build flexible and scalable sites.

FAQs About Using Headless Drupal with React

How do I expose content from Drupal to React?
You can expose content from Drupal to React by enabling the JSON module in Drupal. This module automatically provides RESTful endpoints that expose your content as JSON objects. React can then use these endpoints to fetch content by making HTTP requests to the specific URLs that are mapped to the content you want to retrieve.
How do I fetch data from Drupal in React?
Use axios or a similar HTTP client library to make requests to the Drupal REST API. Parse the JSON response and update React's state.
What kind of content can I manage with Headless Drupal?
Headless Drupal can manage a wide range of content, including articles, pages, media, and more. Since Drupal is highly extensible, you can create custom content types and fields to match the needs of your application. That makes it suitable for anything from simple websites to complex content-driven applications.

Final Words

Headless Drupal with React offers a scalable and flexible solution for building modern websites. By decoupling the frontend and backend, you can leverage the strengths of both technologies to create high-performing sites.

The integration process involves setting up Drupal as a headless CMS, building a React frontend, and handling state management. Considerations such as performance optimization, security, and authentication should also be addressed.

If you want to leverage the complete potential of headless to build robust sites, hire web developers.

Want us to build a well optimized website?

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment