# How to Use React with Python: Architecture, Best Practices, and Integration Patterns

> Learn how to effectively use React with Python. Discover integration patterns, architecture, and best practices for building robust web applications with a React frontend and Python backend.

- Repository: [Meta/react](https://github.com/facebook/react)
- Tags: best-practices
- Published: 2026-02-13

---

**You can integrate React with Python by architecting React as a client-side JavaScript frontend that consumes JSON APIs from a Python backend (FastAPI, Django, or Flask), optionally serving the built React bundle as static files or pre-rendering HTML via Node.js for SEO.**

React is a declarative JavaScript library for building user interfaces maintained in the [facebook/react](https://github.com/facebook/react) repository. While React runs exclusively in the browser or Node.js environments, you can pair it with Python web frameworks by enforcing a clear separation between the frontend presentation layer and the backend API layer. According to the source documentation in [`packages/react/README.md`](https://github.com/facebook/react/blob/main/packages/react/README.md) and [`packages/react-dom/README.md`](https://github.com/facebook/react/blob/main/packages/react-dom/README.md), React handles component rendering and state management, while Python manages data persistence and business logic through HTTP endpoints.

## Architectural Overview: The React-Python Split

A production-ready React with Python architecture divides the system into two distinct layers:

- **Frontend Layer**: React (JavaScript/TypeScript) compiles into a static bundle that executes in the browser. It handles routing, component state, and UI rendering, communicating with Python exclusively via HTTP requests or WebSockets.
- **Backend Layer**: Python frameworks like FastAPI, Flask, or Django expose RESTful endpoints that return JSON data, handle authentication, and perform database operations.

This decoupled approach allows the React frontend and Python backend to scale independently. The React repository's [`packages/react-server/README.md`](https://github.com/facebook/react/blob/main/packages/react-server/README.md) outlines server-side rendering capabilities that can be integrated when SEO or initial page load performance is critical.

## Best Practice 1: Expose Versioned JSON APIs from Python

Expose clean, versioned REST endpoints from your Python backend to enable type-safe communication with React. Use FastAPI or Django REST Framework to define endpoints under `/api/v1/` to prevent breaking changes as your application evolves.

Enable **Cross-Origin Resource Sharing (CORS)** middleware to allow the React development server (typically on `localhost:3000`) to communicate with the Python API (typically on `localhost:8000`).

```python

# backend/main.py

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

app = FastAPI(
    title="React-Python API",
    version="1.0.0",
    openapi_url="/api/v1/openapi.json",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_methods=["*"],
    allow_headers=["*"],
)

class Item(BaseModel):
    id: int
    name: str
    description: str | None = None

_ITEMS = {1: Item(id=1, name="Sample", description="Demo item")}

@app.get("/api/v1/items/{item_id}", response_model=Item)
def read_item(item_id: int):
    return _ITEMS[item_id]

```

## Best Practice 2: Serve the React Bundle as Static Files

After building your React application using `npm run build`, serve the generated static assets ([`index.html`](https://github.com/facebook/react/blob/main/index.html), JavaScript bundles, and CSS) directly from your Python web server. This eliminates the need for a separate Node.js server in production.

In Flask, use `send_from_directory` to serve the build folder and implement a catch-all route that returns [`index.html`](https://github.com/facebook/react/blob/main/index.html) for client-side routing support in single-page applications (SPAs).

```python

# backend/flask_app.py

from flask import Flask, send_from_directory
from pathlib import Path

app = Flask(__name__, static_folder='frontend/build', static_url_path='')

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    if path != "" and (Path(app.static_folder) / path).exists():
        return send_from_directory(app.static_folder, path)
    return send_from_directory(app.static_folder, 'index.html')

```

## Best Practice 3: Configure Development Proxies and Hot Reloading

During development, run React's hot-reloading dev server simultaneously with your Python backend. Configure a proxy to forward API requests from the React dev server to Python, avoiding CORS issues and allowing seamless frontend-backend integration.

For Vite-based React projects, configure the proxy in [`vite.config.ts`](https://github.com/facebook/react/blob/main/vite.config.ts):

```javascript
// frontend/vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:8000',
        changeOrigin: true,
        secure: false,
      },
    },
  },
});

```

The React repository's [`packages/react-refresh/README.md`](https://github.com/facebook/react/blob/main/packages/react-refresh/README.md) documents the Fast Refresh mechanism that preserves component state during hot reloading, which is essential when iterating quickly against a live Python API.

## Best Practice 4: Implement Secure Authentication

Use **JSON Web Tokens (JWT)** or HTTP-Only cookies issued by your Python backend to maintain user sessions. For enhanced security against XSS attacks, store tokens in `HttpOnly` cookies with the `SameSite=Strict` attribute rather than `localStorage`.

On the React frontend, intercept requests using `axios` or `fetch` to attach the JWT to the `Authorization` header:

```typescript
// frontend/src/api.ts
import axios from 'axios';

const api = axios.create({
  baseURL: '/api/v1',
  withCredentials: true, // Required for cookie-based auth
});

api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token'); // Or retrieve from secure cookie
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

```

## Best Practice 5: Leverage Server-Side Rendering for SEO

For SEO-critical applications, pre-render React components to HTML using Node.js before sending the response through your Python backend. The [`packages/react-server/README.md`](https://github.com/facebook/react/blob/main/packages/react-server/README.md) file in the React repository describes APIs for streaming server components.

Implement SSR by launching a Node.js microservice or subprocess from Python that calls `react-dom/server` to generate HTML strings, which your Python framework then embeds into the final response. Alternatively, libraries like **reactpy** allow writing React-style components in Python that compile to JavaScript, though these are best suited for small interactive widgets rather than full applications.

## Best Practice 6: Establish a Testing and Deployment Pipeline

Maintain quality across the stack with comprehensive testing:

- **Frontend**: Use Jest and React Testing Library (documented in the React ecosystem) for unit tests, and Cypress or Playwright for end-to-end tests that validate integration with the Python API.
- **Backend**: Use `pytest` to test API endpoints and validate JSON schemas.
- **Contract Testing**: Use OpenAPI/Swagger specifications generated by FastAPI to ensure the React client and Python API remain synchronized during updates.

For deployment, build the React app into static assets, collect them into your Python project's static directory or upload to a CDN, and deploy the Python service behind a reverse proxy like NGINX or Traefik. Configure the reverse proxy to serve static files directly and forward `/api/*` routes to the Python application.

## Summary

- **Architectural Split**: Run React in the browser and Python on the server, communicating via REST or WebSocket APIs.
- **Static Serving**: Serve the built React bundle from Python (Flask, FastAPI, or Django) to deploy as a single unit.
- **Development Workflow**: Use proxy configurations to route API calls from the React dev server to Python, leveraging Fast Refresh ([`packages/react-refresh/README.md`](https://github.com/facebook/react/blob/main/packages/react-refresh/README.md)) for rapid iteration.
- **Security**: Implement JWT or HTTP-Only cookie authentication issued by Python, with proper CORS configuration.
- **SSR**: Use `react-dom/server` via Node.js for SEO-critical pages, orchestrated through your Python backend.
- **Tooling**: Utilize `eslint-plugin-react-hooks` (from [`packages/eslint-plugin-react-hooks/README.md`](https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md)) and React DevTools ([`packages/react-devtools/README.md`](https://github.com/facebook/react/blob/main/packages/react-devtools/README.md)) to maintain code quality.

## Frequently Asked Questions

### Can React components be written directly in Python?

No, React is a JavaScript library that requires a JavaScript runtime. However, libraries like **reactpy** (formerly react-python) allow you to write component-like structures in Python that compile to JavaScript under the hood. For standard React applications, you write JSX/TypeScript in the frontend and consume Python APIs via HTTP requests.

### How do I handle CORS errors between my React frontend and Python backend?

Enable CORS middleware in your Python framework. In FastAPI, import `CORSMiddleware` and configure `allow_origins` to include your React dev server URL (e.g., `http://localhost:3000`). In production, serve the React bundle from the same domain as your API or explicitly whitelist your production domains.

### Should I use REST or WebSocket for communication between React and Python?

Use **REST** (HTTP) for standard CRUD operations and stateless requests. Use **WebSocket** (via libraries like `socket.io` or native WebSockets supported by Python frameworks like Starlette) for real-time features such as live notifications, chat, or collaborative editing where the server needs to push data to the React client.

### What is the best way to deploy a React-Python application?

Build the React app into static files using `npm run build`, then serve those files from your Python backend or a CDN. Deploy the Python API using Docker or a serverless platform (AWS Lambda, Google Cloud Run), and place a reverse proxy (NGINX, Traefik) in front to handle SSL termination, static file serving, and API routing.