• Stars
    star
    414
  • Rank 104,550 (Top 3 %)
  • Language
    Kotlin
  • License
    Apache License 2.0
  • Created almost 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🗝️ Dotenv is a module that loads environment variables from a .env file

🗝️ dotenv-kotlin

Coverage Status Maven Central Codacy Badge All Contributors

A port of the Ruby dotenv project for Java and Kotlin. Load environment variables from a .env file.

dotenv

Looking for the pure Java version? Get dotenv-java.

Why dotenv?

Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables.

But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. Dotenv load variables from a .env file into ENV when the environment is bootstrapped.

-- Brandon Keepers

Environment variables listed in the host environment override those in .env.

Use dotenv.get("...") instead of Java's System.getenv(...).

Install

Looking for the pure Java variant (no Kotlin), get dotenv-java.

Maven

<dependency>
    <groupId>io.github.cdimascio</groupId>
    <artifactId>dotenv-kotlin</artifactId>
    <version>6.4.1</version>
</dependency>

Previous versions

Gradle

Gradle Groovy DSL

implementation 'io.github.cdimascio:dotenv-kotlin:6.4.1'

Gradle Kotlin DSL

implementation("io.github.cdimascio:dotenv-kotlin:6.4.1")

Usage

Use dotenv.get("...") instead of Java's System.getenv(...). Here's why.

Create a .env file in the root of your project

# formatted as key=value
MY_ENV_VAR1=some_value
MY_EVV_VAR2=some_value

With Java

import io.github.cdimascio.dotenv.Dotenv;

Dotenv dotenv = Dotenv.load();
dotenv.get("MY_ENV_VAR1")

or with Kotlin

import io.github.cdimascio.dotenv.dotenv

val dotenv = dotenv()
dotenv["MY_ENV_VAR1"]

Android Usage

  • Create an assets folder

  • Add env (no dot) to the assets folder.

  • Configure dotenv to search /assets for a file with name env

     val dotenv = dotenv {
         directory = "/assets"
         filename = "env" // instead of '.env', use 'env'
     }
     dotenv["MY_ENV_VAR1"]

Note: The above configuration is required because dot files in /assets do not appear to resolve on Android. (Seeking recommendations from the Android community on how dotenv-kotlin configuration should work in order to provide the best experience for Android developers)

Alternatively, if you are using Provider android.resource you may specify

 directory = "android.resource://com.example.dimascio.myapp/raw"

Flutter Usage

Advices to use the package in the native Android layer prior to the flutter initialization.

  • Create an assets folder inside /android/app/src/main/
  • Add env (not dot) file to the assets folder.
  • Configure dotenv to search ./assets for a file with name env.
	val dotenv = dotenv {
	    directory = "./assets"
	    filename = "env" // instead of '.env', use 'env'
	}
	dotenv["MY_ENV_VAR1"] ?: ""
  • Is a good practice to ignore the env file from the repository. For this purpose you can use the .gitignore inside the android folder

Advanced Usage

Configure

Configure dotenv-kotlin once in your application.

With Java

Dotenv dotenv = Dotenv.configure()
        .directory("./some/path")
        .ignoreIfMalformed()
        .ignoreIfMissing()
        .load();

or with Kotlin

val dotenv = dotenv {
    directory = "./some/path"
    ignoreIfMalformed = true
    ignoreIfMissing = true
}

Get environment variables

Note, environment variables specified in the host environment take precedence over those in .env.

With Java

dotenv.get("HOME");
dotenv.get("MY_ENV_VAR1", "default value");

or with Kotlin

dotenv["HOME"]
dotenv["MY_ENV_VAR1"] ?: "default value"

Iterate over environment variables

Note, environment variables specified in the host environment take precedence over those in .env.

With Java

for (DotenvEntry e : dotenv.entries()) {
    System.out.println(e.getKey());
    System.out.println(e.getValue());
}

or with Kotlin

for (e in dotenv.entries()) {
    println(e.key)
    println(e.value)
}

Configuration options

optional directory

  • path specifies the directory containing .env. Dotenv first searches for .env using the given path on the filesystem. If not found, it searches the given path on the classpath. If directory is not specified it defaults to searching the current working directory on the filesystem. If not found, it searches the current directory on the classpath.

    Java example

     Dotenv
       .configure()
       .directory("/some/path")
       .load()

    Kotlin Dsl example

     dotenv {
       directory = "/some/path"
     }

optional filename

  • Use a filename other than .env. Recommended for use with Android (see details)

    Java example

     Dotenv
       .configure()
       .filename("myenv")
       .load()

    Kotlin Dsl example

     dotenv {
         filename = "myenv"
     }

optional ignoreIfMalformed

  • Do not throw when .env entries are malformed. Malformed entries are skipped.

    Java example

     Dotenv
       .configure()
       .ignoreIfMalformed()
       .load()

    Kotlin Dsl example

     dotenv {
       ignoreIfMalformed = true
     }

optional ignoreIfMissing

  • Do not throw when .env does not exist. Dotenv will continue to retrieve environment variables that are set in the environment e.g. dotenv["HOME"]

    Java example

     Dotenv
       .configure()
       .ignoreIfMissing()
       .load()

    Kotlin Dsl example

     dotenv {
       ignoreIfMissing = true
     }

optional systemProperties

  • Load environment variables into System properties, thus making all environment variables accessible via System.getProperty(...)

    Java example

     Dotenv
       .configure()
       .systemProperties()
       .load()

    Kotlin Dsl example

     dotenv {
       systemProperties = true
     }

Examples

FAQ

Q: Should I deploy a .env to e.g. production?

A: Tenant III of the 12 factor app methodology states "The twelve-factor app stores config in environment variables". Thus, it is not recommended to provide the .env file to such environments. dotenv, however, is super useful in e.g a local development environment as it enables a developer to manage the environment via a file which is more convenient.

Using dotenv in production would be cheating. This type of usage, however is an anti-pattern.

Q: Why should I use dotenv.get("MY_ENV_VAR") instead of System.getenv("MY_ENV_VAR")

A: Since Java does not provide a way to set environment variables on a currently running process, vars listed in .env cannot be set and thus cannot be retrieved using System.getenv(...).

Q: Can I use System.getProperty(...) to retrieve environment variables?

A: Sure. Use the systemProperties option. Or after initializing dotenv set each env var into system properties manually. For example:

Java

Dotenv dotenv = Dotenv.configure().load();
dotenv.entries().forEach(e -> System.setProperty(e.getKey(), e.getValue()));
System.getProperty("MY_VAR");

Kotlin

val dotenv = dotenv()
dotenv.entries().forEach { (key, value) -> System.setProperty(key, value) }

Q: Should I have multiple .env files?

A: No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.

In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.

– The Twelve-Factor App

Q: Should I commit my .env file?

A: No. We strongly recommend against committing your .env file to version control. It should only include environment-specific values such as database passwords or API keys. Your production database should have a different password than your development database.

Q: What happens to environment variables that were already set?

A: dotenv-kotlin will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.

Q: What about variable expansion in .env?

A: We haven't been presented with a compelling use case for expanding variables and believe it leads to env vars that are not "fully orthogonal" as The Twelve-Factor App outlines. Please open an issue if you have a compelling use case.

Q: Can I supply a multi-line value?

A: dotenv-kotlin exhibits the same behavior as Java's System.getenv(...), thus if a multi-line value is needed you might consider encoding it via e.g. Base64. see this comment for details.

Note and reference: The FAQs present on motdotla's dotenv node project page are so well done that I've included those that are relevant in the FAQs above.

Contributors

Contributions are welcome!


Carmine DiMascio

💻 📖 🚇

Arniu Tseng

💻 📖 🚇

Paul Woolcock

🤔

Playacem

💻

Clément P.

💻

Harry Henry Gebel

📖

NyCode

📖

see CONTRIBUTING.md

License

see LICENSE (Apache 2.0)

Buy Me A Coffee

More Repositories

1

express-openapi-validator

🦋 Auto-validates api requests, responses, and securities using ExpressJS and an OpenAPI 3.x specification
TypeScript
914
star
2

generator-express-no-stress

🚂 A Yeoman generator for Express.js based 12-factor apps and apis
JavaScript
579
star
3

generator-express-no-stress-typescript

🚄 A Yeoman generator for Express.js based 12-factor apps and apis using Typescript
TypeScript
348
star
4

dotenv-java

🗝️ Dotenv is a no-dep, pure Java module that loads environment variables from a .env file
Java
308
star
5

py-readability-metrics

📗 Score text readability using a number of formulas: Flesch-Kincaid Grade Level, Gunning Fog, ARI, Dale Chall, SMOG, and more
Python
281
star
6

kotlin-openapi-spring-functional-template

🍃 Kotlin Spring 5 Webflux functional application with api request validation and interactive api doc
Kotlin
177
star
7

essence

Automatically extract the main text content (and more) from an HTML document
Kotlin
105
star
8

uuid-mongodb

📇 Generates and parses MongoDB BSON UUIDs
JavaScript
97
star
9

openapi-spring-webflux-validator

🌱 A friendly kotlin library to validate API endpoints using an OpenApi 3.0 and Swagger 2.0 specification
Kotlin
93
star
10

node-mongodb-fixtures

🍏 Setup and tear down test fixtures with MongoDB.
JavaScript
90
star
11

lambda-zsh-theme

λ Beautiful lambda theme for Zsh
58
star
12

nationalparks_conversation

Chatbots and Watson: Let’s talk about national parks: course source code
JavaScript
46
star
13

java-dotenv

Use dotenv-java or dotenv-kotlin https://github.com/cdimascio/dotenv-java or https://github.com/cdimascio/dotenv-kotlin instead
24
star
14

kotlin-spring-mvc-template

12-factor compliant Spring MVC Kotlin template. Features automatic request/response validation and interactive API doc
Kotlin
22
star
15

react-native-share-sheet

iOS share sheet for React Native
Objective-C
11
star
16

dbpedia-sparql-client

A promisified DBpedia SPARQL client that keeps it simple.
JavaScript
10
star
17

express-openapi-validator-example

simple openapi validation examplewith express-openapi-validator
JavaScript
9
star
18

watson-nlc-spam

Create a spam classifier with Watson Natural Language Classifier.
CSS
9
star
19

gin-openapi

Automatically validates API requests against an OpenAPI 3 spec.
Go
6
star
20

cloudant-upsert

A no-dependency module that adds 'upsert' to Node.js Cloudant
JavaScript
5
star
21

couchinator

🛋️ Fixtures for CouchDB and IBM Cloudant: Create and teardown cloudant dbs
JavaScript
5
star
22

japi-errors

⚡Customizable errors for RESTful and HTTP services.
Java
4
star
23

md5-nodejs

A node module that hashes data to MD5.
JavaScript
4
star
24

mongoose-compose-example

An example to quickly get your up and running with Mongoose and MongoDB on IBM Compose.io.
JavaScript
4
star
25

ya-angular-requirejs-seed

Seed for AngularJs and require.js
JavaScript
3
star
26

essence-web

JavaScript
3
star
27

couchinator-java-wrapper

Fixtures for CouchDB and IBM Cloudant.
Java
3
star
28

sqs-replay

♻️ CLI that replays AWS SQS messages between queues.
Rust
2
star
29

my-projects

A list of newsworthy projects that I led or was key contributor
2
star
30

md5-to-uuid

A node module that converts MD5 hashes to UUIDs.
JavaScript
2
star
31

aws-config-manager

Manage multiple AWS credentials and config files
Go
2
star
32

wcp-errors

Generate normalized http error messages
JavaScript
2
star
33

express-no-stress-openapi3-example

JavaScript
2
star
34

bunyan-decorator

bunyan log decorator for es6 class methods
JavaScript
1
star
35

java-dotenv-example

Java
1
star
36

scripts

Shell
1
star
37

aws-credentials-manager

Utility for managing multiple AWS credentials files.
Shell
1
star
38

woh-deploy

CSS
1
star
39

homebrew-tap

Ruby
1
star
40

rails-example

Ruby
1
star
41

docker-images

Dockerfile
1
star
42

lerna-test

JavaScript
1
star
43

flagger-on

🦩 fast, feature flags with percentage rollout
TypeScript
1
star
44

keras_nns

Python
1
star
45

cdimascio.github.io

Personal website
CSS
1
star
46

nlu-news-web

Sample application using Watson Natural Language Understand and IBM Cloud Functions
JavaScript
1
star
47

mixpanel-export-java

Lightweight export library for Mixpanel
Java
1
star
48

node-api-errors

JavaScript
1
star
49

cdimascio-card

📛 Carmine's card
JavaScript
1
star
50

me-web

JavaScript
1
star
51

vue-webqr

JavaScript
1
star
52

ballparks

Source code for developerWorks article: Create a baseball-themed app powered by Weather Company Data for IBM Bluemix and DBpedia
JavaScript
1
star