java-james / flutter_dotenv

Loads environment variables from `.env`.
https://pub.dartlang.org/packages/flutter_dotenv
MIT License
209 stars 46 forks source link

Rename dotenv.testLoad to dotenv.loadString #85

Open lukepighetti opened 1 year ago

lukepighetti commented 1 year ago

I think we can provide a little more clarity on loading env files from a string by changing the name of this method so it's clear that this is useful outside of test scenarios

Why would you want to load an environment variable from a string in a production app?

Ideally .env files are not baked into the app package assets because they are easy to get access to. We can provide a little bit of obfuscation by loading them into the binary as a compile time string.

ENVIRONMENT=DEVELOPMENT
FASTAPI_KEY=my_public_key
FASTAPI_HOST=localhost
FASTAPI_PORT=8000
// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "app",
      "request": "launch",
      "type": "dart",
      "args": ["--dart-define=ENV=$(cat .env | base64)"] // pull the .env file from filesystem and pipe it to const string via base64
    }
  ]
}
// config.dart
void main() {
  const b64env = String.fromEnvironment('ENV'); // load the base64 encoded .env file
  dotenv.testLoad(fileInput: b64env.fromBase64()); // load it into dotenv, << this is where I think we can add some clarity
  config = Config();
}

class Config {
  final environment = Environment.values.byName(dotenv.get('ENVIRONMENT'));
  final fastApiPort = dotenv.getInt('FASTAPI_PORT').assertPortNumber();
  final fastApiHost = dotenv.get('FASTAPI_HOST').assertNotEmpty();
  final fastApiKey = dotenv.get('FASTAPI_KEY').assertNotEmpty();
}

extension StringExtensions on String {
  String fromBase64() {
    return utf8.decode(base64.decode(this));
  }
}
lukepighetti commented 1 year ago

If we wanted to get even more sugary, we could add dotenv.loadBase64String()