Dynamic subdomain with Flask

If you ever look close to some of the app you where they give subdomain to each of the users or companies. Let's take the example of Hashnode. When I signup with Hashnode they allowed me to take a subdomain name of my choice. Same thing you can do with your flask application with the dynamic subdomain. Flask allows arbitrary subdomain names. Let's take a look at an example

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'hello world'

If you start the server and visit the http://localhost:5000 you will see hello world on your web browser. Now try with subdomain http://acme.localhost:5000 you will still get the output hello world.

Let's make some modification to code to get the subdomain name in our route so we can use in our code.

from flask import Flask

app = Flask(__name__)
app.config['SERVER_NAME'] = "localhost:5000"

@app.route('/')
@app.route('/', subdomain="<subdomain>")
def home(subdomain="default"):
    return f'hello from {subdomain}'

Let's understand all the changes one by one. The first change we made is to add 'SERVER_NAME' config value. Without this value Flask will not be able to differentiate which part of the URL is subdomain and which part is the domain. Here we are giving localhost:5000 if you are running this application on acme.com then this value should in acme.com

The second change is adding extra @app.route('/', subdomain="<subdomain>") this will match all the url with parttern http://*.localhost:5000 and pass the subdomain value as parameter for route function as given name subdomain.

If you try to visit URL without the subdomain the first route function will catch that URL and subdomain value will be the default value. If you have subdomain value the second route will catch that request and subdomain value will whatever value you used as subdomain.