Skip to content Skip to sidebar Skip to footer

Django Static File Serving In Conflict With React Router

My website uses Django as backend and React.js as frontend. Frontend are compiled with react-scripts build so that Django backend can serve it as static files. When running the web

Solution 1:

This has been a headache for me as well.. I managed to fix it by adding the domain of my website to homepage in package.json

{
  "name": "frontend",
  "homepage": "https://example.com/",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/styled": "^11.1.5",
    "@sindresorhus/slugify": "^1.1.0",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
...

I reckon this is not really ideal, especially if you have multiple domains, but it is the easiest way to make it work. . or ./. didn't work for me.

The difference was very subtle. After running a build with homepage: ".", my asset-manifest was looking like this:

{
  "files": {
    "main.css": "/static/css/main.f45be922.chunk.css",
    "main.js": "/static/js/main.a84f15c1.chunk.js",
    "main.js.map": "/static/js/main.a84f15c1.chunk.js.map",
    "runtime-main.js": "/static/js/runtime-main.f8f17c43.js",
...

After running it with "homepage": "https://example.com", it looked like this:

{
  "files": {
    "main.css": "./static/css/main.f45be922.chunk.css",
    "main.js": "./static/js/main.a84f15c1.chunk.js",
    "main.js.map": "./static/js/main.a84f15c1.chunk.js.map",
    "runtime-main.js": "./static/js/runtime-main.f8f17c43.js",
...

That . at the beginning of each file made the difference and my program was able to finally find the statics.

If anyone knows a cleaner way to fix this, please share it!

Solution 2:

instead of trying to change the way you serve static files to avoid conflicts with react statics, you could just name Django's static files route as some thing other than static ,name it staticfiles for example,i.e STATIC_URL = '/staticfiles/'.

you don't need to change the folder name as well so STATIC_ROOT = os.path.join(BASE_DIR, 'static') would work as expected, and later try to redirect /staticfiles route with nginx to your static files folder.

Post a Comment for "Django Static File Serving In Conflict With React Router"