Add secrets to your Streamlit apps

Many Streamlit apps require access to private data like API keys, database passwords, or other credentials. To keep your data safe, it's best practice to never store such credentials directly in your hosted repo. That's why we're excited to introduce Secrets Management - a simple way to securely store your passwords, keys, or really anything you wouldn't want stored in your hosted repo, as secrets that get passed to your app as environment variables.

Below is a quick guide on how to add secrets to your deployed apps – it's really easy to do, we promise 😊.

💡 But before we jump in, Secrets Management is a feature of Streamlit's free sharing platform, so if you're not already using that - request an invite here. Invites are sent out daily, so the wait won't be long!

How to use Secrets Management

Deploy an app and set up secrets

The first thing you'll want to do is go to http://share.streamlit.io/ and click "New app." Next, click the "Advanced settings..." option. A modal with Advanced settings will appear. And here you'll see an input box to insert your secrets.

You'll see an input box into which you can write your secrets

Add your secrets in the "Secrets" field using the TOML format. For example:

# Everything in this section will be available as an environment variable 
db_username = "Jane"
db_password = "12345qwerty"
# You can also add other sections if you like.
# The contents of sections as shown below will not become environment variables,
# but they'll be easily accessible from within Streamlit anyway as we show
# later in this doc.   
[my_cool_secrets]
things_i_like = ["Streamlit", "Python"]

Click save and then your secrets will be added!

Use secrets in your Streamlit app

To use secrets in your app, you'll want to access your secrets as environment variables or by querying the st.secrets dict. For example, if you enter the secrets from the section above, the code below shows you how you can access them within your Streamlit app.

import streamlit as st
# Everything is accessible via the st.secrets dict:
st.write("DB username:", st.secrets["db_username"])
st.write("DB password:", st.secrets["db_password"])
st.write("My cool secrets:", st.secrets["my_cool_secrets"]["things_i_like"])
# And the root-level secrets are also accessible as environment variables:
import os
st.write(
	"Has environment variables been set:",
	os.environ["db_username"] == st.secrets["db_username"])

Edit your app's secrets

Adding or updating secrets in deployed apps is straightforward. You'll want to:

  • Go to https://share.streamlit.io/
  • Open the menu for the app that needs updating, and click "Edit Secrets." A modal will appear with an input box to insert your secrets.
  • Once you finish editing your secrets, click "Save". It might take a few seconds for the update to be propagated to your app, but the new values will be reflected when the app re-runs.

Develop locally with secrets

While the above focuses on deployed apps, you can also add secrets while developing locally. To do this, add a file called secrets.toml in a folder called .streamlit at the root of your app repo and paste your secrets into that file.

💡 NOTE: Be sure to add .streamlit to your .gitignore so you don't commit your secrets!

Let us know how it works for you 🎈

That's it! You'll now be able to add secrets to any of your sharing apps. And if you aren't deploying yet, then remember to request an invite here.

We can't wait to hear what you think and we hope this gives you more flexibility in what you can deploy. We'd love to see your updated apps so make sure to tag @streamlit when you share on Twitter or LinkedIn, and please let us know if you have any questions on the forum!

Resources


This is a companion discussion topic for the original entry at https://blog.streamlit.io/secrets-in-sharing-apps/
4 Likes

My top feature request for several months. Real glad to see this. Thanks!

1 Like

great improvement!

1 Like

Great feature. Thanks for the support Streamlit’s Team :rocket::rocket:

I have one password protected xlsx file, so how can I set (st.secrets)?

xlsx password=“xxxx”

file.load_key(password=“xxxx”) # Use password (Normal).
file.load_key(st.secrets.???) # Use Secrets

Thank you

Regards,
Aktham

After I saw st.secrets is not hashable · Issue #3398 · streamlit/streamlit · GitHub I managed to solve my issue.

Thank you

this was perfect on how to use secrets for the .env!

Hi Everyone,

For the first time, i am trying to connect postgres DB using st.secrets[“postgres”] and end up with invalid directory. Not sure why its saying file not found even though file exists in the look up directory

here is my secrets file structure in vscode on windows
C:\Users\E57036\Desktop\Python_Work\Streamlit_Dashboard.streamlit\secrets.toml

[
postgres
]
host=""
port=
dbname=""
username=""
password=""

here is the code.

import streamlit as st
import psycopg2

def init_connection():
return psycopg2.connect(**st.secrets[“postgres”])

after running my file via streamlit run or as a python file, i am getting file not found error
FileNotFoundError: [Errno 2] No such file or directory:

‘C:\Users\E57036\Desktop\Python_Work\Streamlit_Dashboard\.streamlit\secrets.toml’

@Rami Dear could you solve? I have difficulty to connect it via secrets.

there might be a bug when reading TOML:
I could verify that the secrets.toml file is only read correctly if either in a .streamlit folder under the app.py, or if the .streamlit folder is under the user’s home directory then the error happens if there are sections in the TOML file. Only key=“value” pairs above a bracket line are read, then the parser stops at the bracket to read any key value pairs below. I think the TOML parser is defective.

FYI, in case it’s helpful, you should put singular values in your toml file above key group values, otherwise those singular values will be combined into the key group immediately above. Also the secrets.toml file is only special because it’s available via the Streamlit API and protected in Streamlit Cloud. Otherwise, you can create your own toml files and access them using the toml python package. E.g. for general config (not secrets!), I often do this:

import os
import toml

dir = os.path.abspath(os.path.dirname(__file__))
if os.path.isfile(os.path.join(dir, 'custom_config.toml')):
    service_settings = toml.load(os.path.join(dir, 'custom_config.toml'))
else:
    service_settings = toml.load(os.path.join(dir, 'default_config.toml'))

So, if I’m sharing code with collaborators or on GitHub, I can include the default_config.toml and not my custom_config.toml.

Hey,

I’ve run through the docs but here’s the case. What if I have a json file with my Google Cloud credentials that don’t want to keep on a Git or a server but want to store as a secret? It seems like Streamlit Secrets doesn’t support multi-line TOML format, does it?

The Qs is - how can I assign json’s content to a variable and store it as a multi-line out there in the Secret box?

Thanks,
V

Open the json file in a text editor, copy the text and paste it in the appropriate place inside the secrets box.

This would have been too easy, but Streamlit doesn’t like my TOML syntax. I’ve tried both these “” and ‘’’ for multi-line

Your TOML syntax may be wrong. Did you try feeding it directly to a TOML parser? The delimiters are definitely wrong, but they are not displayed as pre-formatted, so it may be just the discuss editor trying to be helpful (and failing).

Does anyone have any more insight here. If the secret changes, the app can re-rerun but streamlit does not capture the new secret causing the app not to work. Why doesn’t streamlit reboot itself and or how can we automate the reboot so it does capture a changed in secrets.

Is it a correct understanding that Streamlit on Replit does NOT use the new Replit Secrets feature - and that you have to do it via this .toml file?

If you are using st.secrets, it will look for a file at .streamlit/secrets.toml. My guess is that if you create such a .toml file, it will work fine, but you are also welcome to use replit’s built-in secrets, and just access them with os.genenv

Unfortunately server doesnt see any secret keys that uploaded via settings menu. i can run my app locally perfectly. but i get ‘key error’ in logs when running my app. i tried to print out all keys saved in app settings it doesnt print out anything rather empty.