4

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 ?

2
  • Have you tried some of the built in utility functions like send_static_file or url_for('static'...? Commented Feb 7, 2020 at 19:45
  • couldn't figure out how to solve the issue with those two Commented Feb 8, 2020 at 12:48

1 Answer 1

1

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/*)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.