Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 77 ยท REST APIs

Connecting Django with a React Frontend

Connect a React frontend to a Django REST Framework API: CORS with django-cors-headers, fetch with token or session auth, CSRF rules, a Vite proxy and serving the built app.

Django and React solve different halves of an application. Django owns the data, the rules and the security. React owns the interactive screen. They talk over HTTP and JSON, which is exactly what Django REST Framework produces, so connecting them is mostly a matter of three decisions: how the browser is allowed to reach the API (CORS), how the user proves who they are (authentication), and where the built frontend files live in production.

This lesson uses the real DRF and django-cors-headers for the server side. The React side is a small component that runs in your browser against a stand-in fetch, because a live Django server cannot run inside a web page. The code you see is exactly what you would put in a Vite or Create React App project; see the React tutorial for the frontend half.

Two ways to wire them together

flowchart TB
    subgraph A["Option A: two origins"]
      RA["React app<br/>app.example.com"] -- "CORS + token" --> DA["Django API<br/>api.example.com"]
    end
    subgraph B["Option B: one origin"]
      RB["React build served by Django / nginx<br/>example.com"] -- "same-origin, session cookie" --> DB["Django API<br/>example.com/api/"]
    end

Option A splits frontend and API across origins and needs CORS. Option B puts them behind one domain, which removes CORS and makes cookie sessions safe and simple.

If you can choose, Option B is easier and more secure: no CORS, no token storage in JavaScript, and Django's session and CSRF protection work as designed. Choose Option A when the API serves several clients (a mobile app, partners) or when the frontend is hosted on a static CDN.

Step 1: a small API

Any DRF endpoint works. Below is the whole backend for a book list that anyone may read and logged-in users may add to, using token authentication (see DRF Authentication). It also installs django-cors-headers and shows the preflight exchange a browser performs.

Step 2: CORS

Browsers refuse to let JavaScript from http://localhost:5173 read a response from http://localhost:8000 unless the server says so with Access-Control-Allow-* headers. This same-origin policy is a browser rule, so curl and Postman ignore it, which is why "it works in Postman but not in the browser" is the classic first error.

For requests with a JSON body or an Authorization header, the browser first sends a preflight OPTIONS request asking permission. django-cors-headers answers it. Put its middleware as high as possible, above CommonMiddleware:

Python DRF API with token auth and CORS preflight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that for the disallowed origin the server still answered 200. CORS is enforced by the browser: it received the data and then refused to hand it to the page. CORS is therefore not a security feature for your API (anyone can call it with curl); your authentication and permissions are. Keep the allow-list short and exact, never use CORS_ALLOW_ALL_ORIGINS = True outside local development, and never combine a wildcard with credentials.

In a Vite dev setup you can avoid CORS entirely by proxying API calls through the dev server, so the browser sees one origin:

JavaScript
// vite.config.js (read-only)
export default {
  server: { proxy: { "/api": "http://127.0.0.1:8000" } },
};

Step 3: calling the API from React

On the React side, a thin helper keeps the base URL and the token in one place. The component below fetches the list, shows loading and error states, and posts a new book. The fetch used here is a stand-in that mimics the Django API from the previous example (including the 401 when no token is sent), so you can run the exact React code in the editor.

A React component talking to a Django-style API

Try adding a book first without a token and then with letmein. The response codes are the same ones the Django API returns: 401 for missing credentials and 201 for success. Remember that a missing network or a 500 makes fetch behave differently from a 4xx: fetch only rejects on network failure, so always check res.ok.

Authentication: session or token?

Session (cookie) Token (header)
Browser stores An HttpOnly cookie, invisible to JavaScript A string your code must store
CSRF protection needed Yes No (not sent automatically)
Works across domains Needs CORS_ALLOW_CREDENTIALS, SameSite and CSRF_TRUSTED_ORIGINS care Works with plain CORS
Good for Same-site SPA served by Django Mobile apps, third-party clients

With cookie sessions, the browser attaches the cookie to every request automatically, which is why Django requires the CSRF token on POST, PUT, PATCH and DELETE. React must read the csrftoken cookie and send it back in the X-CSRFToken header, and fetch must use credentials: "same-origin" (or "include" across origins):

JavaScript
// read-only
function getCookie(name) {
  return document.cookie.split("; ").find((c) => c.startsWith(name + "="))?.split("=")[1];
}

await fetch("/api/books/", {
  method: "POST",
  credentials: "same-origin",
  headers: { "Content-Type": "application/json", "X-CSRFToken": getCookie("csrftoken") },
  body: JSON.stringify({ title }),
});

Django only sets the csrftoken cookie when a response uses get_token() or the @ensure_csrf_cookie decorator, so expose a small endpoint decorated with ensure_csrf_cookie that the app calls once at start-up. If you go cross-origin, also add the frontend origin to CSRF_TRUSTED_ORIGINS and set CORS_ALLOW_CREDENTIALS = True. Tokens avoid all of this, at the price of storing the token in JavaScript-readable memory; see the storage notes in DRF Authentication.

Step 4: serving the built React app

npm run build produces static files (index.html and hashed JS and CSS). For production you have two common layouts:

  1. Static hosting plus API. Upload dist/ to a CDN or static host and deploy Django separately (Option A). Set the API's CORS_ALLOWED_ORIGINS to the frontend domain.
  2. Single origin. Put the files where Django (through WhiteNoise) or nginx can serve them, and send every non-API path to index.html so client-side routes such as /books/3 survive a refresh:
Python
# urls.py (read-only)
from django.urls import include, path, re_path
from django.views.generic import TemplateView

urlpatterns = [
    path("api/", include("books.urls")),
    path("admin/", admin.site.urls),
    # everything else belongs to the React router
    re_path(r"^(?!api/|admin/|static/).*$", TemplateView.as_view(template_name="index.html")),
]

Point TEMPLATES["DIRS"] and STATICFILES_DIRS at the build folder (see Static Files and Media) and run collectstatic during deploys. Keep the API under a clear prefix like /api/, and make sure unknown /api/ paths return a JSON 404, not the React page.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a request that works in Postman fail in the browser with a CORS error?

    The same-origin policy is a browser rule. Tools like curl and Postman do not enforce it, so the server must send Access-Control-Allow-* headers for browser JavaScript.
  2. 2. What is a preflight request?

    For non-simple requests, the browser sends OPTIONS with Access-Control-Request-* headers. django-cors-headers answers it.
  3. 3. Which approach needs CSRF protection?

    Cookies are attached automatically, so a malicious site could trigger requests. Authorization headers are set by your own code and are not sent automatically.
  4. 4. In a single-origin deployment, why route non-API URLs to index.html?

    React Router handles paths in the browser. On a refresh, the server must return index.html so the router can take over.

Summary

  • Django serves JSON through DRF; React fetches it. The decisions are CORS, authentication and how the build is served.
  • Browsers enforce CORS. Use django-cors-headers with a strict CORS_ALLOWED_ORIGINS list, or avoid CORS with a Vite proxy or a single origin.
  • Token auth suits mobile and cross-origin clients; session auth plus CSRF is simpler and safer for a same-site app.
  • fetch only rejects on network failures, so check res.ok.
  • In production either host the build separately or serve index.html for every non-API path.

Next: Testing Django Apps.