Reflex: Change Configuration Based on Env Mode

Reflex requires different configuration, when running in dev mode and when in prod mode.

Originally you have 2 options:

Set ENV_FILE in terminal

You can set ENV_FILE as a prefix to the command in the terminal:

1
2
3
4
5
6
# run command with env mode 'dev'
$ ENV_FILE=./.env.dev reflex run

# run command with env mode 'prod'
$ ENV_FILE=./.env.prod reflex run --env prod  # run it locally, or
$ ENV_FILE=./.env.prod reflex deploy  # deploy it to the cloud

Set env_file in the rxconfig.py

1
2
3
4
5
6
7
# rxconfig.py
import reflex as rx

config = rx.Config(
    env_file=".env.prod",  # or env_file=".env.dev"
    ...
)

In this case you will have to change the value of env_file yourself, before you run it in different env mode.

Bonus: Set env_file in the rxconfig.py programmatically

With a few lines of code, you can also make it switch automatically, based on the env mode.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
from reflex import constants
import reflex as rx

def get_value_based_on_env_mode(prod=None, dev=None):
    # Note that REFLEX_ENV_MODE variable is only set
    # with 'reflex run', but not with 'reflex deploy'.
    env_mode = os.environ.get(
        "REFLEX_ENV_MODE",
        constants.Env.PROD
    )
    is_dev_mode = env_mode == constants.Env.DEV

    return dev if is_dev_mode else prod

config = rx.Config(
    env_file=get_value_based_on_env_mode(
        prod=".env.prod",
        dev=".env.dev"
    ),
    ...
)