Full Stack
.......................................................................................................
Signup to be notified when the Fluent React course
launches in MARCH 2025 .
(and get started with a 5-part free React course in the mean time.)
...........................................................................................

Learn How to Integrate your React App with a Django Backend using a Sample Blogging Project

1: What You will Learn

In this guide, you will learn about:
 
  • How Django renders pages

  • How React renders its components

  • How to develop React and Django side by side (and make it easy to merge later in production)

  • How to create a production build of your React app

  • How to integrate your React app's production build with your Django backend project

  • Best practices for integrating your frontend/React app with a (Django) backend

  • What you can do next to upskill your full-stack web development

Whether you are a Django backend or React frontend web developer, it is important that you know how both the backend and frontend apps work independently and how they work together as one unit: i.e in a "Full Stack" setup.
 
You should also know how to integrate your frontend React app with your backend Django web project into a production-ready full-stack web project.

By the time you finish working through this developer guide, you should have learned (maybe even mastered):

  • How your backend web app works and what it is/should be responsible for in a full-stack setup

  • How your frontend web app works and what its functions are as part of a "Full stack" web project

  • How to integrate your React frontend app with your Django backend web project

  • How to develop your Django project and your React web app together to make both easy to manage, run and integrate (when the time comes.)

  • Best practices for integrating a frontend app with a backend project/app (with a focus on React and Django.)

  • Tips and advice for solidifying your full stack web development skills

  • Some technical resources to help you become a better React and Django Full Stack web developer.

 

Along the way, you will learn about how to create a build of your React app, integrate it with your backend Django project so you can deploy it to production as one single unit that runs within the Django web server.

 

2: How Django Renders Pages

So, how does your Django web project work?

 

A basic understanding of this is critical if you are going to trying to integrate your React frontend app with a Django backend.

 

So, how does Django work?

 

Here's how ...

 

  1. A user types in or clicks on a link to a page or submits a form on your Django website. (This could be in dev or after deployment to production. The concept is the same.) This initiates an `HTTP Request` from the client to the Django web backend.

  2. Django detects takes the `HTTP Request` and looks for a matching URL (from its list of `urlpatterns`).

  3. If no URL path matches, this causes an error, such as a `404` (`Page Not Found`), etc. If the requested URL matches one in Django's list of `urlpatterns`, the view (function or class) associated with that URL path is called to execute.

  4. The matching view takes the `HTTP Request` object (and any data within it that is needed to properly serve the request).

    The view then queries the database to see if there is an object/row that matches what was requested.

    1. If there were matching results, the result(s) are put into a `Context Object` (usually a Python dictionary of key-value pairs) and rendered in an HTML file/template that renders the page for that view.

    2. If there were no matching object(s) in the database, an appropriate error (put in a `Context Object`)is rendered in the same (or different) HTML template.

      Whether the result of the database query was a success or failure, the view will return an `HTTP Response` object (that includes, among other things, the queried DB data or the generated error) to the requested web page when it renders the matching template.

  5. The user interacts with what's rendered in the UI of the requested web page.

 

All these steps happen in a matter of miliseconds (depending on how fast your app and DB queries are).

 

3: How React is Rendered

But, what about your frontend React web app? How does it work?

 

There are two scenarios for how React works.
 
  • In Development: During development, your React web app functions like a standalone app with its own dev server (started with either `npm start` or `yarn dev`, for example).

    When a user clicks on an internal link, React checks for the matching `Route` (typically configured in the root `App.js` component file) so that it can load the matching (instance of the) component to render for the request route.

    If there was no matching `Route` at the requested URL, an error (or blank page) may be returned and/or rendered (depending on how the developer chose to handle such a situation.)

  • In Production: Before deploying your Full Stack web app to production, you have to integrate the frontend React app with the backend Django app. The integration involves creating a production build of the React app and then adding the generated files to the backend Django app to be run from a single URL path (in the Django app) and served by a Django view.

    As such, in production, your whole React app (and any complex logic, fancy UI, state management system, API calls and what-have-you) is just a single file served by a Django view at a specific URL path.

    The React routes will still work but are more like navigating between different sections of a web page than between different pages of a site. But the user needs not care about that underlying reality.
 
To the developer, the whole frontend app is a Single Page App (aka an "SPA"), but to your website's user, it's a fully-functioning multi-page app. The mechanics do not and (for the sake of your User Experience) should not matter.

 

4: Developing React and Django Side by Side

So, how do you develop a full stack Django-React web project together?

 

Different developers have different approaches (that work; to each his own!).

 

I am of the (strong) professional opinion that:

 

  • Your full-stack Django-React web project should have one root folder. That folder will be the Django project's root folder. So, if you are developing a Django project called `blogsite`, your top-level/root folder for your full-stack Django-React project should be that root `blogsite/` folder.

  • Your Django project should be organized into apps (as per Django convention anyway). This prevents code smells and convolutions. So, you can have a `blog` app under the `blogsite` Django project. This `blogsite/blog/` folder will then contain all the files, folders and assets of the `blog` app.

  • Your React (or any frontend: Angular, VueJS, Svelte, etc.) app should be inside the Django app (`blog`, in our case) that you are developing a React frontend for. Some people just put the React app adjacent/besides the `blog` app inside the root `blogsite/` folder.

  • Your React (or any frontend) app should be inside the `static/` folder of your Django app. Why? Because, you will be working with CSS, JS and JSX (which isn't "really" HTML, but an extension of JavaScript).

    As per some of the Django best practices in How to Manage Static Files (in Django), any static assets (files or folders) should be inside the Django app's `static/` folder. So, in our case, you should create a `static` folder inside the `blogsite/blog/` app folder.

    Inside the `blogsite/blog/static/` folder, you can then bootstrap/initialize your React app using Create-React-App (CRA) or Vite (or any other available/supported tools) from right inside the `blogsite/blog/static/` folder.

    So, you could endup with your frontend blog React app at `blogsite/blog/static/blog-app/`. The name of the folder of your React app (which we called `blog-app` here) just depends on what name you gave the React app when first creating it (using CRA or Vite). It doesn't matter what you call it; just name it clearly and responsibly.

  • Add a "proxy" to the backend Django APIs server (e.g. `http://localhost:8000/api/posts/`) in your React app's `package.json` file. This lets you make HTTP calls from your React app to your Django project's API endpoints without further configurations (or more complex CORS hurdles) and all the ever-annoying errors that you will encounter in your terminal and browser console.

 

So, to demonstrate, if you have a Django project called `blogsite`, your full stack Django-React folder structure will look like this:
 
  • The Django project is the root `blogsite/` folder (or "package" in Python terms, since it contains an `__init__.py` file)

  • The Django app is at `blogsite/blog/` (which is the folder/package that contains the folders and files for the Django project's `blog` app.)

  • The React app is at the `blogsite/blog/static/blog-app` folder (which contains all the files and folders for the React app.)

 

To summarize, your frontend React app (`blog-app`, in our case) will be inside the `static/` folder of the `blog` app of the `blogsite` Django project. That is, the React app will be at `blogsite/blog/static/blog-app/`. Please, review that until it is clear.

 

Once you have your React app inside the `static/` folder of your Django app, you can now set out to develop both your Django project and your React app side by side without either affecting the other's development or functionality.

 

And, then, to run:

  • Your Django Project: Just use the usual `manage.py runserver` command from inside the root directory of the Django project. This will start the backend Django project and any Django-based APIs you have developed.

  • Your React App: Use the `npm start` or `yarn dev` (if using Vite) commands to start the React dev server.

  • Both Simultaneously: Just run both the Django and React server-starting commands (in their proper places) and let both your Django and React web servers run in tandem. This way, for example, you can make calls from your React app to your Django backend APIs without issues, God willing.
 
This (i.e. running both the Django and React dev servers side by side) is in development only.

 

In Production, you will only need to start the Django server. The React app will be run from a single Django view and served in a Django URL path/route.

 

5: Create a React Build

Once you have developed your Django APIs and have developed your React app and made sure both work together (as described above), it is time to create a "production build" of your app.

 

What's a "production build"?

 

As you develop your React app, you create folders and files for your components, APIs, custom hooks (if you need any), routes, stylesheets and so on. But in production, you will just need to run the whole React app from a single page (which is where we get the "Single Page App" term from).

 

For the whole React app to be served from a single HTML file and a single Django view, you will need to combine and minify the whole React app (its components, hooks, routes, APIs, stylsheets and anything else) into as small as it can get.

 

Generating the production build will necessitate the removal of whitespace from your code, the obfuscation of a good chunk of it and more.

 

To delve into the details of what is involved in the background process when you try to create a production build of your React app, please, see the documentation on https://react.dev .

 

So, let's take a look at how to create a production build of your React app.

 

  1. `cd` into the root directory of your React app. In our case, that would be the `blogsite/blog/static/blog-app/` folder.

  2. Run `npm run build` (or `yarn build`, if using Vite instead of CRA) on your terminal/command line.

 

This will take a few moments to collect together the various parts of your React app, including components, API files, custom hooks, stylesheets, state management code, etc.

Once it is all done (minification, obfuscation, etc.), you should have a brand new `build/` folder besides the `src/` folder of your React app. In our case, this will be `blogsite/blog/static/blog-app/build/`.

 

The generated production build folder will contain, among other things:
 
  • `static/` Folder: This will contain one folder each for your `JS` and `CSS` files.

  • `index.html`: This is the HTML file that you will pass to the Django view that will render the React app.

    This `build/index.html` file will contain links/references to:

    • The `build/static/main.<random_code>.chunk.js` File: This is basically the whole React app's code that you wrote: components, APIs, state management, JSX markup, custom stylesheets, etc. It is all minified now and optimized for production use.

    • the `build/static/css/main.<random_code>.chunk.css` File: This stylesheet contains all your defined CSS styles.

    • Other CSS and JS files that need to be loaded and run from the `build/index.html` file.

 

You can try looking at the markup for the generated `build/index.html` file and the referenced JS and CSS files in it. (The referenced CSS and JS files are actually inside the generated `build/static/` folder.)

 

Now that you have generated a production build of your React app, you should now copy the `build/` folder's contents (`index.html`, `static/` folder) into the `blogsite/blog/` app's folder.

 

This you can do in a few steps that I will outline below.

 

6: Integrate your React App's Build with the Django Backend

To copy over the generated `build` folder of your React app, please, follow these steps:

 

  1. Copy the `js/` and `css/` Folders FROM the generated `build/static/` folder INTO the `blogsite/blog/static/blog/` folder.

  2. Create a New `templates` Folder inside the `blogsite/blog/` app's folder.

    So, `cd` into the `blogsite/blog/` folder and run `mkdir templates` from your terminal.

  3. Create a `blog` Folder inside the new `templates` folder like this:

    `cd templates && mkdir blog`. This way, your `blog` app's `templates` folder is at `blogsite/blog/templates/blog/`. This is called "namespacing" in Django.

  4. Copy the `build/index.html` HTML file INTO the newly-created `blogsite/blog/templates/blog/` folder.

    At this point, you should now have a `blogsite/blog/templates/blog/index.html` file (which is an exact copy of the generated `build/index.html` file). Henceforth, we will just refer to this file as `blog/index.html`.

  5. Update the Paths to your Static Assets (CSS and JS files) inside the `blog/index.html` file to point to the `blog/static/blog/js/` folder (for the JS files) and the `blog/static/blog/css/` folder (for the CSS files).

    Perform this update on all the references to the CSS and JavaScript files from inside the `blog/index.html` file.

  6. Create a Django View inside the `blogsite/blog/views.py` file that will render the `blog/index.html` file.

    So, open up the `blog/views.py` file and add this piece of code:
    
    from django.shortcuts import render
    
        # Create your views here.
        def index(request):
            return render(request, 'blog/index.html')
    
  7. Create a URL Path for the New `index()` View.

    Note that, you can call this view `home`, `react` or anything else. I just chose to name it simply and memorably. Do what applies (or appears logical) to you best.

    So, open the `blogsite/blog/urls.py` file and add this to the `blog` app's `urlpatterns` list:

    
        from django.urls import path
        from blog import views
    
        app_name = 'blog'
    
        urlpatterns = [
            path('', views.index, name='index'),
        ]
    
  8. Load the URL in Your Browser.

    Remember that you specified (in the `blogsite/urls.py` file) that your `blog.urls` will be loaded from the `/blog/` root. So, any URLs (like the `blog:index` we just created) should be loaded from the `/blog/` root URL.

    And, since you are loading your React app from the root of the `blog/` URL, you should open your browser to `http://localhost:8000/blog/`. This should load your React app (as it was when you started its server in dev using `npm run start` or `yarn dev`.)

    If you encounter errors, debug the `blog/index.html` file and make sure the paths to the referenced static CSS and JS files (which are, basically, your React app's code) are correct. Then, try loading the URL again.

    Rinse and repeat the debugging until your React app loads properly from your Django view.

    At this point, commit your `blogsite/blog/static/` and `blogsite/blog/templates/` folders and their content into the current `blogsite/` project's repo. Then, push your code to whichever code hosting service you use: Github, Bitbucket, etc.

    What you have done up to this point is actually to test that your React app would work error-free as part of your backend Django project when you deploy it to production.

    But you haven't deployed it to production yet.

    There is just one thing left for you to do ...

  9. Deploy your Project to your Chosen Hosting Provider.

 

Now that your frontend React app is fully integrated into your backend Django project, create a new (or use an existing) virtual server.

Configure , pull your Django project's code (that's already got the React app integrated into it following the above eight (8) steps). Then, configure your Nginx or Apache (or whatever other ones you use) and deploy your app to the world.

While you are at it, send me a link so I can take a look. Tweets and LinkedIn tags/mentions are welcome. :)

 

And, ladies and gentlemen, that's how you integrate a frontend React app with a Django web backend project.

 

If you have got questions, comments or suggestions about how to best approach integrate React with Django, please, share it in the comments below. Shukran! Thank you! Gracias! :)

 

7: Best Practices for Integrating React with Django

 

How you exactly go about integrating your React frontend with a Django backend project will depend on factors such as your professional experience, proven expertise, personal preference and, to a large extent, the specific challenges and needs of your web project.

 

But, no matter what the details of your web project, here are some best practices for integrating a React frontend app with a Django backend project without going bunkers in the process or accumulating too much code smell and refactoring headache down the line.

 

Some of these best practices include:

  • Plan for Eventual Integration: As you build your Django and React apps in development, do so with the understanding that you will eventually need to integrate both the backend project and the frontend React app into one unified full-stack web project.

    For example, you can use the same CSS framework (like Bootstrap, Material Design, etc.) in both your backend (Django) project's templates as your React components.

    This way, once you integrate your React app into your Django backend (which uses Bootstrap styles), you won't run into issues where the style names you used in your React components are not valid (or don't serve the same purpose) as the style names used by the CSS framework in your Django templates.

    And, if you have a custom stylesheet that you are using, just copy it into your React app (during development) so that your React components can use those styles in their JSX markup.

    And, copy the same stylesheet into the Django app's `static/` folder. Then, link to it from the `build/index.html` file after you copy it to the backend Django app's `templates/` folder. (Remember that this copied `build/index.html` file is what will be rendered as your React app in production after the React-Django integration is completed.)

  • Build both as One Full Stack Project: Put your React app inside the `static/` folder of the Django app you will be building as the web backend. Just like we did with putting the frontend React `blog-app` inside the `blogsite/blog/static/` folder (in the Django `blog` app.)

    One reason for this is for easy reference. You want to keep the related frontend React app inside the backend web app that it will be eventually integrated into (to serve as its UI).

    Another reason is that, depending on the complexity and need of your website/platform, you may have a Django project with multiple apps (each with models and API services) and a matching React app to consume those API endpoints and render the UI of the app.

    In this case, for example, the backend `social` app can have its React UI app inside its `social/static/social-app` folder and the backend `dashboard` app can have its related React UI app inside the `dashboard/static/dashboard-ui` folder and so on.

    There is better modularity and it is easier to track errors, add new functionality (to either the backend or frontend app) and it is much simpler to isolate (or even remove) an app.

    For example, "taking out" the `dashboard` app (and its related React `dashboard-ui` app) is as simple as removing the `dashboard` app from the Django settings' `INSTALLED_APPS` list and removing reference to it in the root/project `urls.py` file.

  • Use One Repo for your Backend and Frontend: Unless you have an unusual use case, keep both your Django backend project and the frontend React app in the same repo. Any developer (working on either end) can clone, pull, commit code and push to the same branch..

    You may use different git branches during development until you fully-test and merge both the backend and frontend prior to deploying to production.

    But, don't keep two different repos for the same project. It is enough to have to deal with one repo in production. Don't overcomplicate this by always having to pull your React app (which is in a different repo) into your Django project (during the integration in dev) or in production (if that's where you plan to generate the production build and do the full-stack integration).

  • Test Production Build Locally Before Deployment: There are instances when your React app may not correctly integrate into your backend Django web project. For instance, you may not have setup the API URL in the React app correctly.

    When you created a build and try to run the generated `build/` folder's contents (`index.html` file and `js/` and `css/` folders' contents), you may not have updated the paths to the static assets in the `index.html` file to conform to where you have copied the generated `js/` and `css/` folders into the `static/` folder of the Django app.

    But if you test the production build and resulting integration with the Django backend project locally, you will discover any errors that will also be triggered in production that will prevent your website from running properly when deployed.

    So, test it locally and don't let the urge and excitement to deploy to prod make you cause big (but preventable) development blunders along the way.

  • Test After Deployment to Production: Once you deploy your integrated React-Django full stack project to production, don't be in a haste to share the link with the world or with your social media networks and followers.

    First, test it thoroughly to make sure everything works well and as intended. If all is well, breathe out nicely. If there are errors, take it down, fix errors, test the integration and re-deploy it to production again.

    In a much more advanced or technically-experienced company, your deployment process may involve deploying your integrated web project to your `test` servers/environment, then `staging` before finally deploying to your `production` servers. If this is part of your deployment pipeline, do follow it to the "t".

    But whether you have the luxury of having a dedicated team of QA testers (and a sophisticated deployment pipeline), are writing test suites or are doing manual testing, do the testing. A thorough web application testing approach will save you a lot of nightmares, customer complaints and PR woes in the (possibly very near) future.

  • Document your Integration Process: It is always exhilarating to learn something new and put it into practice successfully, such as integrating your React app with a backend Django web project. You would have done so much googling (for missed steps, errors, technical bottlenecks, etc.) that the search results, console logs and terms become so familiar to you that they would be invaluable acquaintances if they were human.

    But one problem that I have run into (again and again) is that I learn a new framework, tool or process and implement it correctly. Then, I find myself trying to go over some documentation months or years down the line just so I can replicate the same app or process. Maybe you are also guilty of this. One near-guranteed solution to this is to document your processs.

  • Outline the steps you took (which one first and followed by which), which packages, libraries or frameworks you installed, what settings or configurations you had to do (and into which file and for what package, library or framework), etc.

    Also, document the bugs, warnings and errors you encounter along the way (including what triggered it or at what steps) and how you resolved it. Bookmark and add any articles or StackOverFlow threads that were vital in helping you resolve the issue.

    To help other developers (at, below or above your experience level; it doesn't matter) have a "ready reference" for how to do the same thing that you just did (and documented), you can write an article, create a video or put together a slideshow of the steps you took and how you achieved your intended result(s). This piece of content will serve both as a quick reference (for you) and an invaluable resource to the developer community that you belong to and the world of developers at large.

    Also, documenting your process will help any team members or other developers tasked with working on the same project know exactly how to take the project from development to production. This applies irrespective of which backend web framework (Django, Flask, ExpressJS, Rails, etc.) that you used and which frontend framework or library (ReactJS, Angular, Vue, etc.) that you used.

    And, if you publish your documented process, that content alone will save you a good amount of interview time and push you through the "gatekeepers" when your name (and published content) come up during a candidate screening/selection process. You would have authority written all over your name.

    So, document your React-Django integration process for you, your fellow team members, the future you and the developer community at large.

 

8: What's Next?

So, what steps should you take next after learning how to integrate your React app with a Django web backend?

 

There are a few things you could (and should) do:
 
  • Take an existing Django project:

    • Create APIs with full CRUD functionality

    • Add a React frontend app to the project (and make it consume the APIs from the Django backend, so that it uses that data in the React app's components)

    • Follow the steps in this guide to integrate the React frontend with the Django backend.

  • Create a new web project that has a Django backend and a React frontend.

    Have the Django backend serve the APIs and the React frontend render the UI.

    Then, create a production build of the React app and integrate it with the Django backend ready to be deployed to production as one singular full-stack web project.

  • Take a fully-integrated Django-React full stack web project and deploy it to production.

    You can get a free VPS machine on AWS, DigitalOcean (for two months) or Google Cloud Platform (GCP) (for 90 days). Check for other Cloud solutions, if you are not particularly inclined to use any of these.

    Learn how to configure a server and deploy a web project to it. (The cloud providers mentioned all provide step-by-step tutorials on how to do that. DigitalOcean seems to have more beginner-friendly and useful tutorials, whether you decide to go with its service or not.)

    Share your link with friends, colleagues and in your developer community and see what you learn from the criticism (both constructive and sharp-witted). Then, do it again.

  • Take an existing React app. Create a Django backend for it (to serve APIs, handle authentication, etc.).

    Then, integrate the React app into the new Django web backend project and deploy it to production.

    Rinse and repeat until you master how to integrate Django and React into a fully-functioning and seamless full stack web project.

  • At every step (in each of the above web projects), and no matter what you do, document your process.

 

Till the next developer guide is published, please, create some quality web apps and help make the world a better place for us all.

 

I wish you all the best in your endeavors.

 

9: Technical Reference

Here are some technical resources to help you review creating web apps using Django and React.js and best practices while doing so.
 

Developer Guides Related to This One:

Please, share your insights, concerns and experiences about the topic and/or content of this article.