|
| 1 | +--- |
| 2 | +sidebar_position: 7 |
| 3 | +title: 🌱 Environments |
| 4 | +--- |
| 5 | + |
| 6 | +# Environments 🌱 |
| 7 | + |
| 8 | +--- |
| 9 | + |
| 10 | +The ability of configuring different environments is necessary for any real world applications. |
| 11 | + |
| 12 | +The application needs to be able be configured to run a development environment, or a staging one |
| 13 | +and ultimately, a production one. |
| 14 | + |
| 15 | +There are many ways that different environments can be achieved in a Dart Frog application, the |
| 16 | +out of the box one is by making the use of environment variables, which is a feature provided |
| 17 | +directly from the Dart SDK. |
| 18 | + |
| 19 | +As seen in the Dependency injection example, middleware can be used to provide dependencies |
| 20 | +to the application. |
| 21 | + |
| 22 | +Following that approach, the snippet bellow can be used to exemplify how a database client that |
| 23 | +can be is configured through different environments can be provided to the application. |
| 24 | + |
| 25 | +```dart |
| 26 | +Handler middleware(Handler handler) { |
| 27 | + return handler |
| 28 | + .use(provider<CardsRepository>((_) { |
| 29 | + return DatabaseClient( |
| 30 | + dbUrl: Platform.environment['DB_URL'], |
| 31 | + dbUser: Platform.environment['DB_USER'], |
| 32 | + dbPassword: Platform.environment['DB_PASSWORD'], |
| 33 | + ); |
| 34 | + }), |
| 35 | + ); |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | +Then, when running the server, those variables can be passed along directly on the Dart Frog |
| 40 | +commands, like: |
| 41 | + |
| 42 | +For development server: |
| 43 | + |
| 44 | +```bash |
| 45 | +DB_URL=... DB_USER=... DB_PASSWORD=... dart_frog server |
| 46 | +``` |
| 47 | + |
| 48 | +For production server |
| 49 | + |
| 50 | +```bash |
| 51 | +DB_URL=... DB_USER=... DB_PASSWORD=... dart build/server.dart |
| 52 | +``` |
| 53 | + |
| 54 | +For convenience, these variables can also be exported in the current session. |
| 55 | + |
| 56 | +:::warning |
| 57 | +Commonly used in Flutter applications, accessing variables through `String.fromEnvironment` in |
| 58 | +a Dart frog application will not work, that method is meant to accesses variables set by the dart |
| 59 | +compiler or runtime, which doesn't apply on a Dart frog application. Due that |
| 60 | +`Platform.environment` should be used instead. |
| 61 | +::: |
0 commit comments