How to Use Strapi With React

How to Use Strapi With React

How to Use Strapi With React

Building modern web applications requires fast, flexible, and scalable solutions. Strapi, one of the most popular open‑source headless CMS platforms, helps developers create custom APIs effortlessly, while React enables building dynamic and interactive user interfaces. When used together, they empower developers to build robust, scalable full‑stack applications with clean architecture and high performance.

In this in‑depth guide, you will learn how to use Strapi with React, how to fetch Strapi APIs, how to build dynamic pages, how to configure permissions, how to handle authentication, and how to structure your project for long‑term scalability. The tutorial is written for both beginners and experienced developers.

If you need expert help with full‑stack development, you can hire AAMAX. AAMAX is a full‑service digital marketing and development company offering MERN Stack Development, Web Development, SEO, and Digital Marketing services.

Introduction to Strapi and React Architecture

Strapi is a headless CMS, meaning it provides a backend to manage content while exposing it through APIs (REST or GraphQL). React is the frontend layer where you display that content.

This separation allows:

  • Faster development
  • Improved performance
  • Cleaner architecture
  • High scalability
  • Easy integration with mobile apps, websites, or third‑party services

How Strapi and React Work Together

  1. Strapi manages content (blogs, products, pages, user data).
  2. Strapi exposes APIs automatically.
  3. React fetches this data using fetch, axios, or React Query.
  4. React displays the content dynamically in UI components.

This headless approach is now the standard for modern web development.

Step 1: Setting Up the Strapi Backend

First, install Strapi using NPX:

npx create-strapi-app@latest strapi-backend

Navigate to your project:

cd strapi-backend
npm run develop

Strapi will open the admin dashboard at:

http://localhost:1337/admin

Create your admin user and you're ready to begin.

Creating a Collection Type (Example: Blog Posts)

  1. Open Content-Type Builder
  2. Create a Collection Type
  3. Name it: Post
  4. Add fields:
    • Title (Text)
    • Slug (UID)
    • Content (Rich Text)
    • Featured Image (Media)
    • Category (Relation)
  5. Save and Strapi will auto‑restart.

Adding Content in Strapi

  1. Go to Content Manager
  2. Choose the Post type
  3. Add a new entry
  4. Publish it

Strapi gives a draft & publish workflow, so make sure content is published so React can fetch it.

Step 2: Configuring API Permissions for React

By default, Strapi prevents public API access.

To allow your React frontend to fetch data:

  1. Go to Settings → Users & Permissions → Public
  2. Enable:
    • find
    • findOne
  3. Save permissions

Now your API is ready for frontend requests.

Example API Endpoints

GET http://localhost:1337/api/posts
GET http://localhost:1337/api/posts/1

To include media or relations:

GET http://localhost:1337/api/posts?populate=*

Step 3: Setting Up the React Project

Create a new React app:

npx create-react-app react-frontend

Navigate:

cd react-frontend
npm start

Your React app will run at:

http://localhost:3000

Now you can connect it to Strapi.

Step 4: Fetching Data From Strapi in React

Strapi automatically exposes data through REST APIs, making it simple to fetch content.

Option 1: Fetching With Native fetch

Inside a component:

import { useEffect, useState } from "react";

function BlogPage() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch("http://localhost:1337/api/posts?populate=*")
      .then(res => res.json())
      .then(data => setPosts(data.data));
  }, []);

  return (
    <div>
      <h1>Blog</h1>
      {posts.map(post => (
        <div key={post.id}>
          <h2>{post.attributes.title}</h2>
        </div>
      ))}
    </div>
  );
}

export default BlogPage;

Option 2: Fetching With Axios

import axios from "axios";

axios.get("http://localhost:1337/api/posts?populate=*")
  .then(res => console.log(res.data));

Using Axios is more convenient for error handling and interceptors.

Option 3: Fetching With React Query

React Query provides caching, revalidation, and performance optimization.

import { useQuery } from "@tanstack/react-query";

function BlogPage() {
  const { data, isLoading } = useQuery({
    queryKey: ["posts"],
    queryFn: () =>
      fetch("http://localhost:1337/api/posts?populate=*").then(res => res.json())
  });

  if (isLoading) return "Loading...";

  return (
    <div>
      {data.data.map(post => (
        <h2 key={post.id}>{post.attributes.title}</h2>
      ))}
    </div>
  );
}

React Query is recommended for production apps.

Step 5: Displaying Media From Strapi in React

Images uploaded in Strapi come with a relative URL, so you need to prepend the Strapi base URL.

const imageUrl = "http://localhost:1337" + post.attributes.featuredImage.data.attributes.url;

Render the image:

<img src={imageUrl} alt="featured" />

Step 6: Handling Slugs and Dynamic Routing in React

If you're building a blog or product catalog, you need dynamic pages.

Example: Dynamic Route With React Router

Install:

npm install react-router-dom

Define routes:

<Routes>
  <Route path="/" element={<BlogPage />} />
  <Route path="/post/:slug" element={<SinglePost />} />
</Routes>

Fetching a Single Post by Slug

Inside SinglePost:

import { useParams } from "react-router-dom";

function SinglePost() {
  const { slug } = useParams();

  const [post, setPost] = useState(null);

  useEffect(() => {
    fetch(`http://localhost:1337/api/posts?filters[slug][$eq]=${slug}&populate=*`)
      .then(res => res.json())
      .then(data => setPost(data.data[0]));
  }, [slug]);

  if (!post) return "Loading...";

  return (
    <div>
      <h1>{post.attributes.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.attributes.content }} />
    </div>
  );
}

export default SinglePost;

React can now dynamically render pages from Strapi content.

Step 7: Authentication With Strapi and React

Strapi provides built‑in JWT authentication.

Register User

POST /api/auth/local/register

Login User

POST /api/auth/local

Example React login handler:

axios.post("http://localhost:1337/api/auth/local", {
  identifier: email,
  password: password
}).then(res => {
  localStorage.setItem("token", res.data.jwt);
});

Using JWT in Requests

axios.get("http://localhost:1337/api/user-posts", {
  headers: {
    Authorization: `Bearer ${localStorage.getItem("token")}`
  }
});

This allows React to access protected Strapi routes.

Step 8: Creating Custom API Endpoints in Strapi

You may need custom logic for:

  • filtering data
  • advanced queries
  • user‑specific content
  • secure operations

Create custom controllers in:

/src/api/<collection>/controllers

Example:

module.exports = {
  async customRoute(ctx) {
    ctx.body = "Custom API works!";
  }
};

Define routes:

{
  "method": "GET",
  "path": "/custom-route",
  "handler": "controller.customRoute"
}

React can fetch:

fetch("http://localhost:1337/api/custom-route")

Step 9: Best Folder Structure for React + Strapi

A recommended structure:

react-frontend/
  src/
    components/
    pages/
    hooks/
    utils/
    services/
    context/

Strapi API calls should be moved into services/api.js:

export const fetchPosts = async () => {
  const res = await fetch("http://localhost:1337/api/posts?populate=*");
  return res.json();
};

This helps maintain clean code and reusability.

Step 10: Filtering, Searching, and Sorting Data in Strapi

Strapi provides powerful query options.

Filtering:

/api/posts?filters[category][name][$eq]=Technology

Search:

/api/posts?filters[title][$contains]=javascript

Sorting:

/api/posts?sort=createdAt:desc

React can dynamically build queries based on user input.

Step 11: Deployment Strategy for Strapi + React

Deploy independently:

Strapi can be deployed on:

  • DigitalOcean
  • Render
  • AWS EC2
  • VPS (Nginx + PM2)
  • Docker

React can be deployed on:

  • Vercel
  • Netlify
  • Cloudflare Pages
  • AWS Amplify

Environment Variables

Do not hard‑code API URLs.

React .env:

REACT_APP_API_URL=https://your-strapi-domain.com

Use it:

fetch(`${process.env.REACT_APP_API_URL}/api/posts`);

Step 12: SEO Considerations for React + Strapi

React alone is not SEO‑friendly unless using:

  • React Helmet
  • prerendering
  • server‑side rendering (Next.js preferred)

You can add:

import { Helmet } from "react-helmet";

<Helmet>
  <title>{post.attributes.title}</title>
</Helmet>

However, if SEO is a priority, consider Next.js instead of pure React.

Final Thoughts

Using Strapi with React creates a highly scalable and flexible full‑stack architecture. Strapi handles content management and API creation, while React delivers exceptional UI performance and interactivity. With the right approach---proper permissions, API structure, dynamic routing, authentication, and clean project architecture---you can build anything from blogs to eCommerce stores, dashboards, SaaS apps, and enterprise tools.

If you need professional help with Strapi, React, or full MERN stack development, you can hire AAMAX, a leading agency providing Web Development, SEO, and Digital Marketing solutions.

Related Blogs

Top Business Directories & Listing Sites in Togo

Top Business Directories & Listing Sites in Togo

Explore the best Togo business directories and worldwide listing sites to improve online presence, attract customers, and grow your business.

Top Business Directories & Listing Sites in Hungary

Top Business Directories & Listing Sites in Hungary

Comprehensive guide to Hungary business directories and global listing sites for better online exposure, reviews, and local search rankings.

Top Business Directories & Listing Sites in Israel

Top Business Directories & Listing Sites in Israel

List your business on top Israeli and international directories to increase discoverability, trust, and online growth opportunities.

Top Business Directories & Listing Sites in Austria

Top Business Directories & Listing Sites in Austria

Comprehensive resource covering Austria’s best business directories and international listing platforms for maximum online exposure.

Top Business Directories & Listing Sites in Belarus

Top Business Directories & Listing Sites in Belarus

Explore the best Belarus business directories and worldwide listing platforms. Learn how local and global citations help businesses grow visibility an...

Top Business Directories & Listing Sites in Switzerland

Top Business Directories & Listing Sites in Switzerland

Grow your Swiss business online with the best business directories and global listing sites designed for visibility and customer engagement.

Need Help? Chat with Our AI Support Bot