Preact

Find out how to integrate Strapi with Preact

Preact logo

Introduction to Preact and Strapi

Preact is a lightweight JavaScript library for creating interactive user interfaces. With a footprint of just 3kB, it delivers the tools you need without unnecessary overhead. If you're familiar with React, you'll find Preact's API to be virtually identical, making it easy to adopt.

By integrating Preact with Strapi, you can create applications that are both fast and feature-rich. Preact efficiently handles client-side rendering, while Strapi manages your content and data on the server side. With this integration, you can build seamless user experiences and streamline your development process.

Why Use Strapi with Preact

Pairing Preact with Strapi lets you build fast, efficient web applications with a powerful backend for content management and a responsive frontend.

Lightweight and Fast Frontend

With Preact's small size—only 3kB—you can create applications that load quickly and provide a smooth user experience. Despite its minimal footprint, Preact maintains compatibility with most React libraries and tools, so you don't lose out on functionality.

Powerful Content Management with Strapi

Strapi provides a flexible and customizable backend for managing content. Its intuitive admin panel and support for REST and GraphQL APIs make it easy to fetch and display content in your Preact application. By making content management straightforward, Strapi enhances your app's capabilities, enabling features like personalized content through AI integration with its headless CMS, boosting user engagement and satisfaction across platforms.

Strapi's commitment to open-source principles is evident from its inception as an open-source project, and it continues to actively support and nurture its community. Strapi provides various resources such as the Strapi Community Forum, Strapi Community Stars, and extensive documentation, which collectively ensure that developers have the necessary resources and support system to effectively use and contribute to the platform. Moreover, understanding Strapi's business model provides insight into its long-term viability and commitment to the developer community.

The Strapi community insights from active contributors highlight the vibrant ecosystem surrounding Strapi, offering support and collaborative opportunities.

Seamless Integration

Integrating Preact with Strapi is straightforward because Preact's API closely mirrors React's. You can adapt existing guides for integrating React with Strapi to your Preact project with minimal changes, speeding up development and reducing the learning curve.

This seamless integration has been demonstrated in various projects, leading to significant Strapi project success. Companies like Mug & Snug have utilized this integration to develop social e-commerce platforms, while Google and WallDecaux launched a real-time outdoor ad campaign with 55 million impressions using Strapi.

Key Features of Preact

Preact is a lightweight alternative to React, offering similar functionality with a much smaller footprint. At just 3kB, Preact delivers performance and efficiency, making it ideal for applications where speed and bundle size are critical.

Preact's compatibility with the modern React API allows you to use familiar concepts like components, props, and state. However, there are differences to note, such as using h instead of React.createElement, and class instead of className in JSX.

Preact includes built-in state management and supports hooks for functional components. Some advanced features of React may not be available or might require additional libraries when using Preact.

Best Practices of Integrating Preact With Strapi

Following best practices when integrating Preact with Strapi ensures a smooth development process.

Configure CORS in Strapi

To allow your Preact application to communicate with Strapi, configure Cross-Origin Resource Sharing (CORS) settings. In Strapi, scroll down to the Cross-origin resource sharing (CORS) block and select Edit. Add a JSON configuration for CORS, specifying allowed headers, methods, and origins. Save your changes after editing.

Use Environment Variables for API URLs

Store your API base URLs in environment variables to keep your code clean and make it easier to switch between environments. This practice enhances security and simplifies configuration management.

Implement Error Handling and Loading States

Include error handling and loading states in your Preact components to improve user experience. Provide feedback to users when data is loading or if an error occurs.

Utilize Preact Hooks for Functional Components

Use Preact's hooks, such as useState and useEffect, in your functional components. Hooks simplify state management and side effects, leading to cleaner and more maintainable code.

Optimize Strapi Queries

Optimize your queries to retrieve only the necessary data from Strapi. Adjust your API requests to include query parameters that limit fields and reduce payload size, which can improve performance. For additional performance improvements, consider strategies outlined in this image optimization guide.

Secure Your Strapi API

Set up appropriate permissions in Strapi to secure your API endpoints. Implement authentication in your Preact app if needed.

Handle Authentication in Preact

Manage the JSON Web Token (JWT) in your Preact app if your Strapi API requires authentication. Store the token securely and include it in your API requests' headers.

Configure Deployment Settings

Before deploying, update the API URLs to match your production Strapi instance, and ensure environment variables are correctly set. Verify both your Strapi backend and Preact frontend are properly configured for production.

By following these best practices, you can build robust applications. Community contributions, such as Kwinten's involvement with Strapi, highlight how developers can enhance and troubleshoot integrations. PostHog has utilized Strapi to create a community forum, roadmap, and changelog, transforming their static marketing website into an interactive platform with community forums, profiles, a feature request board, and a content publishing portal without third-party tools.

Getting Started With Preact

To begin using Preact, set up a new project using the Preact CLI.

Installing the Preact CLI

Ensure Node.js and npm are installed. Install the Preact CLI globally:

npm install -g preact-cli

Creating a New Preact Project

Create a new app with:

preact create default my-preact-app

Replace my-preact-app with your project name. This command scaffolds a new Preact project using the default template.

Exploring the Project Structure

Navigate to your project:

cd my-preact-app

The main directories include:

  • src/: Application source code.
  • components/: Reusable components.
  • index.js: Entry point.
  • index.html: HTML template.

Running the Development Server

Start the server:

npm run dev

Your app runs at http://localhost:8080. Open this URL to view your application.

Creating a Simple Component

Let's create a component that uses state. In src/components, create Counter.js:

import { h } from 'preact';

import { useState } from 'preact/hooks';

const Counter = () => {

  const \[count, setCount\] = useState(0);

  return (

    <div>

      <p>Count: {count}</p>

      <button onClick={() => setCount(count + 1)}>Increment</button>

    </div>

  );

};

export default Counter;

Updating the App Component

Import the Counter component in src/components/app.js:

import { h } from 'preact';

import Counter from './Counter';

const App = () => (

  <div id="app">

    <h1>Hello, Preact!</h1>

    <Counter />

  </div>

);

export default App;

Save the files, and your app will display the counter component.

Building for Production

When ready to deploy, build your app:

npm run build

The optimized files are in the build/ directory, ready for deployment.

Frequently Asked Questions

Use Preact's hooks (useState, useEffect) with Fetch or Axios to retrieve Strapi content. Preact's React-compatible API means most React-Strapi patterns work with minimal modification.

Preact's 3kB size makes it ideal for performance-critical Strapi frontends. It provides the same component model as React with significantly smaller bundle sizes and faster initial loads.

Configure Strapi's middleware to allow requests from your Preact development server's origin. Add the development URL to the CORS allowed origins in Strapi's middleware configuration.

Yes, use preact-render-to-string for server-side rendering. Fetch Strapi content on the server, render to HTML, then hydrate on the client for full interactivity.

Use preact-router for client-side routing, fetching content based on route parameters from Strapi's API. Implement dynamic routes that match your Strapi content structure.