Tutorial: Host a Python Backend and React Frontend for Free
Tutorial: Host a Python Backend and React Frontend for Free
Learn how to host a Python script (backend) and a React frontend for free using popular platforms with free tiers. This tutorial, updated as of April 2025, guides you through setting up a full-stack application with a REST API backend and a static React frontend, perfect for your Google Blog project.
Overview
In this tutorial, we'll:
- Host a Python backend using PythonAnywhere or Render.
- Host a React frontend using Vercel or Netlify.
- Integrate the two using API calls with CORS handling.
- Provide code snippets and step-by-step instructions.
React Frontend: A static site (HTML, CSS, JS) after building.
Python Backend: A server running a Python script (e.g., Flask or FastAPI).
Prerequisites
- Basic knowledge of Python, JavaScript, and React.
- Git installed and a GitHub account.
- Node.js and npm installed for React development.
- Python 3.8+ installed for backend development.
Step 1: Prepare Your Application
Before hosting, set up your backend and frontend locally.
1.1 Python Backend (Flask)
Create a simple Flask API to serve data.
# app.py
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Enable CORS for React frontend
@app.route('/api/data', methods=['GET'])
def get_data():
return jsonify({'message': 'Hello from Python!'})
if __name__ == '__main__':
app.run(debug=True)
Create a requirements.txt
file:
flask==2.3.3
flask-cors==4.0.1
gunicorn==22.0.0
Note: Use gunicorn
for production, not app.run()
.
1.2 React Frontend
Create a React app using npx create-react-app my-app
and set up an API call.
// src/App.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState('');
useEffect(() => {
axios.get('https://your-backend-url/api/data')
.then(response => setData(response.data.message))
.catch(error => console.error('Error:', error));
}, []);
return (
<div>
<h1>React + Python App</h1>
<p>Backend Response: {data}</p>
</div>
);
}
export default App;
Install axios
:
npm install axios
Add a proxy for local development in package.json
:
"proxy": "http://localhost:5000"
Build the app for deployment:
npm run build
This generates a build
folder with static files.
Step 2: Host the Python Backend
Choose a free platform to host your Flask backend.
Option 1: PythonAnywhere (Free Tier)
Features: 512MB disk space, Flask support, free subdomain (e.g., yourusername.pythonanywhere.com
).
- Sign up at pythonanywhere.com.
- Go to the "Files" tab and upload
app.py
andrequirements.txt
. - In the "Web" tab, create a new Flask web app and select your Python version.
- Edit the WSGI configuration file to point to
app.py
(PythonAnywhere provides a template). - Open a Bash console and install dependencies:
pip install -r requirements.txt
- Reload the web app to deploy.
- Note your backend URL (e.g.,
https://yourusername.pythonanywhere.com/api/data
).
Limitation: Limited CPU time, no sudo
access. Some libraries may not work.
Option 2: Render (Free Tier)
Features: Supports Flask/FastAPI, free subdomain (e.g., yourapp.onrender.com
), SSL.
- Sign up at render.com.
- Create a new "Web Service" and connect your GitHub repo with the backend code.
- Set the runtime to Python and the start command:
gunicorn -w 4 -b 0.0.0.0:8000 app:app
- Ensure
requirements.txt
is in the repo root. - Deploy; Render installs dependencies and provides a URL.
Limitation: Free tier spins down after 15 minutes of inactivity, causing delays. 750 free hours/month.
Step 3: Host the React Frontend
Host your static React app on a free platform.
Option 1: Vercel (Free Tier)
Features: 100GB bandwidth, auto HTTPS, subdomain (e.g., yourapp.vercel.app
).
- Sign up at vercel.com and connect your GitHub repo.
- Create a new project, select your repo, and configure:
- Framework Preset: Create React App
- Build Command:
npm run build
- Output Directory:
build
- Deploy; Vercel provides a URL.
- Update your React app’s API calls to the backend URL (e.g.,
https://yourusername.pythonanywhere.com/api/data
).
Limitation: 100GB bandwidth/month, no server-side rendering in free tier.
Option 2: Netlify (Free Tier)
Features: 100GB bandwidth, auto HTTPS, subdomain (e.g., yourapp.netlify.app
).
- Sign up at netlify.com and connect your GitHub repo.
- Create a new site, select your repo, and configure:
- Build Command:
npm run build
- Publish Directory:
build
- Build Command:
- Deploy; Netlify provides a URL.
- Update API calls to your backend.
Limitation: 100GB bandwidth/month, limited serverless functions.
Step 4: Integrate Frontend and Backend
Ensure your React frontend communicates with the Python backend via API calls.
- Update your React app’s API base URL to the deployed backend URL.
- Verify CORS is enabled on the backend. For Flask,
flask-cors
is already included in our example. - Test by making requests from the frontend to the backend.
If using FastAPI instead of Flask, add CORS middleware:
# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourapp.vercel.app"],
allow_methods=["*"],
allow_headers=["*"]
)
@app.get("/api/data")
async def get_data():
return {"message": "Hello from Python!"}
Step 5: Test and Deploy
Local Testing
- Run the backend:
python app.py
orgunicorn app:app
. - Run the frontend:
npm start
. - Test API calls locally to ensure they work.
Deploy
- Deploy the backend to PythonAnywhere or Render.
- Deploy the frontend to Vercel or Netlify.
- Update the frontend’s API URL to the backend’s deployed URL.
- Visit the frontend URL and verify functionality.
Recommended Free Stack
- Backend: PythonAnywhere (easy, no Docker) or Render (modern, Git-based).
- Frontend: Vercel (fast, developer-friendly) or Netlify (great UI).
- Why: Generous free tiers, Git integration, and reliable for Python-React apps.
Troubleshooting
- CORS Issues: Ensure CORS is enabled and API URLs are correct.
- Spin-Down Delays: Render’s free tier spins down; use PythonAnywhere for always-on hosting.
- Resource Limits: Optimize code (minify JS, reduce dependencies).
- Logs: Check PythonAnywhere server logs or Vercel build logs for debugging.
Conclusion
You’ve now learned how to host a Python backend and React frontend for free! This setup is ideal for small projects, prototypes, or learning. For production apps, consider paid plans for better performance and custom domains.
Have questions or run into issues? Leave a comment below, and I’ll help you out!
Comments
Post a Comment