Zed
Zed

Reputation: 5931

Serving React app with Flask fails with static files

I am trying to do a very simple thing, serve a react app with Flask, but all the suggestions in other threads doesn't really work and it's becoming frustrating.

I have a directory structure that looks like this:


client
      build
           static
           index.html

So all JS/CSS files are in the static directory. I followed the usual advice and come up with this:

app = Flask(__name__, static_folder='../client/build')

@app.route("/")
def serve():
    """serves React App"""
    return send_from_directory(app.static_folder, "index.html")

@app.route("/static/<path:path>")
def static_proxy(path):
    """static folder serve"""
    file_name = path.split("/")[-1]
    dir_name = os.path.join(app.static_folder, "/".join(path.split("/")[:-1]))
    return send_from_directory(dir_name, file_name)

and with that, it does serve index.html from the build directory when I open the root url. However, the trouble comes when the index.html loads, because all the static files are references like this static/js/file.js, that translates into GET request - localhost/static/js/file.js, and could not be found. I figured out that in order to hit static/js/file.js successfully, I would need to use this url localhost/build/static/js/file.js.

So, I in order to access static files, I would have to add the build prefix everywhere. Is there a better way to solve this ?

Upvotes: 4

Views: 824

Answers (1)

Zed
Zed

Reputation: 5931

After so many attempts and trying different options, I gave up on solving this with Flask. I found that I could just build the react app like this

export PUBLIC_URL=/build

npm run build

to produce all references to have the path that flask expects (build/static/*)

Upvotes: 1

Related Questions