63

I'm using Flask with React. I'd like to create a catch all route similar to something like this (although this doesn't work):

@app.route('*')
def get():
    return render_template('index.html')

Since my app will use React and it's using the index.html to mount my React components, I'd like for every route request to point to my index.html page in templates. Is there a way to do this (or is using a redirect the best way)?

dace
  • 5,819
  • 13
  • 44
  • 74

1 Answers1

90

You can follow this guideline: https://flask.palletsprojects.com/en/1.1.x/api/#url-route-registrations

from flask import Flask
app = Flask(__name__)

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return 'You want path: %s' % path

if __name__ == '__main__':
    app.run()
Community
  • 1
  • 1
I. Helmot
  • 1,140
  • 8
  • 8
  • 8
    Does anyone know if this will just catch all otherwise unspecified route paths, or if it will override other more specific routes? Like if right above this I had a route for `/mypath` would it still be there or would this overrule it by catching everything? – theferrit32 Jan 25 '19 at 21:55
  • @MaxWiederholt Replace the return statement with `return render_template('index.html')`. – Lalo Sánchez Feb 13 '19 at 01:16
  • 6
    @theferrit32 You can still use other routes, so `/mypath` should still work. Only non-defined paths will be re-routed to the catch all. – Lalo Sánchez Feb 13 '19 at 01:24
  • 4
    I don't see the same route pattern in the provided url, also this route works only for /, using something else returns 404. What could be the possible reason? – makkasi Sep 28 '19 at 11:21
  • 1
    Doesn't work for path's like `/foo/bar.baz`. – Alexander Kleinhans Dec 08 '19 at 04:43
  • @Displayname Nested paths like `/foo/bar.baz` work perfectly well for me using this pattern. – mackstann Jan 10 '20 at 23:01
  • 3
    Doesn't work for POST requests. – Throw Away Account Feb 14 '20 at 04:57
  • 2
    It works well but if you have some settings to handle static contents it doesn't work. for example: Flask(__name__,static_url_path='',static_folder='web/static', template_folder='web/templates') I think the problem is around the static_url_path setting. – István Döbrentei Oct 11 '20 at 09:28
  • 1
    for POST just add `@app.route('/', methods=['GET', 'POST'])` – Aiman Alsari Sep 08 '21 at 19:57
  • Updating the url from this answer to a newer version: https://flask.palletsprojects.com/en/2.0.x/api/#url-route-registrations – Andrew Anderson Jan 11 '22 at 19:37