java-james / flutter_dotenv

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

Not requiring .env as an Asset - point to global env #47

Open khari998 opened 2 years ago

khari998 commented 2 years ago

Is it possible to make it so .env is not required as an asset? For Flutter web, I am deploying my site to Netlify and of course my .env file is hidden from the Github hosted repository that Netlify is pulling my website code from. So every time my site tries to build, it says the .env file is missing. I can define environment variables in Netlify but currently I have no way of accessing them as dotenv only points to a local .env.

The ideal solution would be for dotenv to use my .env file in development and use my global environment variables from Netlify in production. Even if you were able to get dotenv to recognize global environment variables, it still would require the .env to not be recognized in pubspec.yaml as a required asset so that there aren't build errors when building the website.

Currently this makes dotenv practically unusable for my project unless I am able to figure out how to recreate the .env file from the global environment variables in my root folder in Netlify before the build starts

vanshg395 commented 2 years ago

Same issue, is there any fix?

khari998 commented 2 years ago

@vanshg395 This took me down a long rabbit hole. But long story short, I ended up moving all my api calls away from Flutter web to server functions. You can use a regular nodejs server hosted on another instance that will run the code requiring secrets from the .env.

In my particular case, I'm using Netlify to host my Flutter Web application. I ended up installing npm in my flutter project just to use the netlfiy dev environment. You can use netlify dev and point to your web/build folder in order to tell it where to find the Flutter Web project. From there I just had all of my API calls in flutter point to my functions in netlfiy. Netlify dev hosts the functions for me on its own port so no need to worry about CORS. Netlify Dev is great and it will load keys directly from a .env file in the project so thats what I use. Only caveat is that you are going to likely be developing using some of that code using the built version of your project on the new Netlify port which means no hot reload and that is a pain.

I also tried doing this the hard way where I tried recreating the .env file at the build command when it was deployed to my web host. But this situation still didn't get around CORS. So I found it more useful to have secrets handled only by the server and not on client code. You can get away with having secrets on client code in mobile because you don't have to worry about CORS, but once you start dealing with CORS requests on Flutter Web, its better to just move the calls out of the client code completely and offload that work to another server.