avatarJen-Hsuan Hsieh (Sean)

Summary

This article provides a guide on connecting a React front-end application with a Django back-end API server to create a single-page application (SPA) and deploy it on Heroku.

Abstract

The article serves as a step-by-step tutorial for integrating a React application with a Django backend to deploy a single-page application on Heroku. It begins by acknowledging the need to run two servers for React and Django in development but aims to consolidate this into a single server for production. The author outlines the process of initializing both Django and React applications, connecting them, and serving the React frontend through Django. Key steps include setting up Django and React projects, building the React app for production, configuring Django to serve the React app, and ensuring proper static file handling in a production environment using WhiteNoise. The article emphasizes the importance of setting the DEBUG flag to false for production and provides guidance on configuring Django settings for static files. The author, Sean, shares this as a personal note and invites feedback while also promoting related articles and topics.

Opinions

  • The author advocates for using a single server in production to serve both the React frontend and Django backend, simplifying deployment.
  • It is recommended to use WhiteNoise for serving static files when DEBUG is set to false in Django for a production environment.
  • The article is presented as a learning resource, with the author encouraging feedback and sharing personal reflections on the development process.
  • The author emphasizes the educational aspect by referencing previous articles in a series and suggesting further reading on related topics.
  • Sean, the author, values community engagement and professional growth, as evidenced by his invitation for feedback and his sharing of a LinkedIn profile and Facebook page for further interaction.

Build Single page application with React and Django Part 2— Connect React App with Django App

Copy right@A Layman

Overview

The last article we mentioned that how to deploy Django application to Heroku.

We have to run two servers if we want to use React App as a SPA server and use Django app as an APIs server. What if we only want to launch one server on the machine?

Agenda

This article is a note to solve this problem. One of the ways to connect the React App and Django App is to render the React page from the Django server.

It will include the following topics.

About this series

The target of this series is to build a ReactJS single page application(SPA) with Django API server and deploy on Heroku.

1.Initialize Django App and React App

In the first stage, we have to initialize Django App and React App.

Create Django App

  • We can also check the detail of the Django app creating from the following article

1.Use pip to install Django

pip install django

2.Create a Django App by using the following commands

django-admin startproject djangoReact
cd django-react-app
python manage.py startapp app

3.Create requirements.txt

Django==3.0.3
whitenoise==5.0.1
gunicorn

4.Edit app/views.py

from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
    return HttpResponse('Django example')

5.Create routes for the app: create app/urls.py

from django.urls import path
from . import views
urlpatterns = [
    path("", views.index, name = "index")
]

6.Edit routes for the project: edit djangoReact/urls.py

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
    path('', include('app.urls')),
    path('admin/', admin.site.urls),
]

7.Edit djangoReact/settings.py

INSTALLED_APPS = [
    'app.apps.AppConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
...

8.Run the Django app

python manage.py runserver

Open the browser and visit http://127.0.0.1:8000

Copy right@A Layman

Create React App

1.Create a React App by using the following commands in the folder

npm init react-app django-react-web

2.Run the React app

npm start
Copy right@A Layman
  • The file structure looks like the following screen-shot
Copy right@A Layman

2.Connect CRA(React App) with Django App

We run React App and Django App successfully. The next step is to render React page from the Django App.

1.Create the production of the React app

npm run build

2.Edit Package.json

"proxy": "http://localhost:8000"

2.Edit app/urls.py

from . import views
urlpatterns = [
    ...
    path("react", views.react, name="react")
]

3.Edit app/views.py

...
import os
import logging
from django.conf import settings
index_file_path = os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')
...
def react(request):
    try:
        with open(index_file_path) as f:
            return HttpResponse(f.read())
    except FileNotFoundError:
        logging.exception('Production build of app not found'

4.Edit djangoReact/settings.py

REACT_APP_DIR = os.path.join(BASE_DIR, 'django-react-web')
STATICFILES_DIRS = [
    os.path.join(REACT_APP_DIR, 'build', 'static'),
]

5.Run the Django app

python manage.py runserver

Visit http://127.0.0.1:8000/react

Copy right@A Layman

3. Set the DEBUG flag to false (for production)

According to the official document, we should never deploy a site into production with DEBUG turned on.

source: https://docs.djangoproject.com/en/4.2/ref/settings/

However, the response of requests for static files will return Not found when we set the DEBUG false. This is because Django not serving your static files in debug False.

Use WhiteNoise to serve static files

One of the solution is to install and setup WhiteNoise. The package can provide the ability for Django to serve static files.

1.Install the package

pip install whitenoise

2.Update the djangoReact/settings.py

  • The STATIC_URL is the fragment of the URL path for static files requests
  • The STATICFILES_DIRS is the customized path that we can specify for the project. Files there will be copied to the STATIC_ROOT
  • The STATIC_ROOT is the destination of the static files collected from the whole project. Django will look static files from the folder when requests come
DEBUG = False

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    #Should add WhiteNoiseMiddleware after the SecurityMiddleware
    'whitenoise.middleware.WhiteNoiseMiddleware',
    ...
]

STATIC_URL = '/_next/'
STATIC_ROOT = os.path.join(REACT_APP_DIR, 'out')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
#STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(REACT_APP_DIR, '.next'),
]

3. Execute the following command before excuting runserver. The Django will copy static files from STATICFILES_DIRS to STATIC_ROOT.

python manage.py collectstatic

Summary

Thanks for your patient. I am Sean. I work as a software engineer.

This article is my note. Please feel free to give me advice if any mistakes. I am looking forward to your feedback.

Please feel free to clap if this article can help you. Thank you.

You can also subscribe my page on Facebook.

Related topics

How to use the two-way binding in Knout.js and ReactJS?

Learn how to use SignalR to build a chatroom application

My reflection of :

IT & Network:

Database:

Software testing:

Debugging:

DevOps:

References

Django
React
Single Page Applications
Software Development
JavaScript
Recommended from ReadMedium