Hi everyone! I'm working on an app for my nonprofit job and I need some help with securely connecting to a MongoDB server. I've recently learned Dart, but I'm stuck on the login process. I initially thought about storing usernames and hashed passwords in MongoDB, which is also necessary for other data in the app. However, I ended up having to hard-code the database password in my main.dart file, which I know isn't secure. Is there a better way to manage the MongoDB connection without hardcoding sensitive information? I don't have a lot of experience, so any advice would be greatly appreciated. Thanks!
4 Answers
Great instincts! Keep your MongoDB connection string in an environment variable and access it at runtime. Use a .env file for local development that’s excluded from version control, and for production, set the variables in your hosting environment or a secrets manager. Also, consider applying user restrictions and credential rotation practices for added security.
First things first, if you’ve uploaded your code with the hardcoded credentials to a public repository, revoke those MongoDB credentials immediately and create new ones! Generally, secrets should not be stored in your source code. Use environment variables to securely manage your database connection strings. Just check your deployment setup for the best way to set these variables!
You’ll want to set environment variables on your hosting platform where your app runs. I don’t know Dart well, but there are methods to read environment variables in Dart, which you can look up. The setup varies by hosting environment, so let me know where you're deploying, and I can help with more specifics!
Exactly! Each platform has its own way, so once you figure that out, it’ll be straightforward.
Definitely avoid hardcoding passwords! A great way to keep your MongoDB credentials safe is by using environment variables. Set your password in an environment variable, and your application can read it at runtime. Just make sure not to include these variables in your code repository, like Git, to prevent exposure.

Thanks for the tip! I’ll make sure to revoke those credentials right away.