Connecting React and Django Rest Framework: Quick Guide
By Andrew on 8/19/2024
This guide offers a quick, straightforward approach to connecting React with Django Rest Framework. This guide will help you set up a basic project that demonstrates the Django React integration.
Let’s get started!
Backend: Django Rest Framework Setup
-
Install Django and DRF:
pip install django djangorestframework django-cors-headers
-
Create Django project and app:
django-admin startproject backend cd backend python manage.py startapp api
-
Add to INSTALLED_APPS in backend/settings.py:
INSTALLED_APPS = [ # ... 'rest_framework', 'corsheaders', 'api', ]
-
Add to MIDDLEWARE in backend/settings.py:
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # ... other middleware ]
-
Add CORS settings in backend/settings.py:
CORS_ALLOW_ALL_ORIGINS = True # Only for development
-
Create a simple API view in api/views.py:
from rest_framework.views import APIView from rest_framework.response import Response class TestView(APIView): def get(self, request): return Response({"message": "Connected to DRF!"})
-
Set up URL in api/urls.py:
from django.urls import path from .views import TestView urlpatterns = [ path('test/', TestView.as_view()), ]
-
Include in backend/urls.py:
from django.urls import path, include urlpatterns = [ path('api/', include('api.urls')), ]
Frontend: React Setup
-
Create React app:
npx create-react-app frontend cd frontend
-
Install axios:
npm install axios
-
Replace src/App.js content:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; function App() { const [message, setMessage] = useState(''); useEffect(() => { axios.get('http://localhost:8000/api/test/') .then(response => setMessage(response.data.message)) .catch(error => console.error('Error:', error)); }, []); return ( <div className="App"> <h1>React + DRF Connection Test</h1> <p>{message}</p> </div> ); } export default App;
Running the Application
-
Start Django server:
python manage.py runserver
-
In a new terminal, start React app:
npm start
Visit http://localhost:3000 to see your React app connected to Django Rest Framework.
Important Security Note
The setup described in this guide is for development purposes only. For production, you should not use CORS_ALLOW_ALL_ORIGINS = True
. This setting can expose your application to security vulnerabilities.
Instead, the recommended approach for production is to use a reverse proxy setup with nginx or Traefik. This allows you to route both your frontend and backend through the same domain, eliminating the need for CORS entirely.
Production-Ready Solution
If you’re looking for a fully featured, secure, production-ready setup that properly handles the connection between React and Django Rest Framework, check out slimsaas.com. SlimSaaS offers a pre-configured boilerplate that includes a proper reverse proxy setup, authentication, payments, along with many other features to jumpstart your development.
Build Faster