Guide · Open source
How to use godotenv: load .env files in Go
Updated · written with AI from the project's own documentation and checked against our catalogue data
godotenv is a Go library and command-line tool that reads key=value pairs from a .env file and sets them as environment variables. It is a Go port of Ruby's dotenv project. This guide shows how to install it, load a .env file in a Go app, read values without changing the environment, and run a command with variables loaded from a file.
Quick start
- 1Install godotenv. Run go get github.com/joho/godotenv in your module to add the library, or run go install github.com/joho/godotenv/cmd/godotenv@latest for the command-line tool.
- 2Create a .env file. Add key=value lines to a file named .env in your project root.
- 3Call Load in main. Call godotenv.Load() and handle the returned error before reading any values.
- 4Read values with os.Getenv. Use os.Getenv with each key name, such as S3_BUCKET.
- 5Choose a read method if you do not want to change the environment. Use godotenv.Read, Parse, or Unmarshal to get a map instead.
- 6Run a command with the CLI. Use godotenv -f with a path to load a file and then run your program.
Install godotenv as a library or command-line tool
godotenv can be added to a Go project as a library or installed as a standalone command. Both install paths come from the project README and use the Go toolchain.
The README notes that the go get -tool form requires Go 1.24 or newer. The other commands do not list that requirement.
- Library: use go get to add the package to your module.
- Command-line tool: use go install to put the godotenv binary in your Go bin directory.
go get github.com/joho/godotenv
go install github.com/joho/godotenv/cmd/godotenv@latestCreate a .env file in your project root
Put your application settings in a file named .env in the root of your project. Each line holds one key=value pair. Keep secrets and environment-specific values here rather than in your code.
The file supports comments, export prefixes, and YAML-style key: value lines. The README shows that a comment at the end of a line is allowed.
- Lines starting with # are comments.
- export before a key is accepted.
- YAML-style lines such as FOO: bar are also accepted.
S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE
# I am a comment and that is OK
FOO=BAR # comments at line end are OK too
export BAR=BAZLoad the .env file in a Go app
Call godotenv.Load() early in main, check the error, and then read values with os.Getenv. By default, Load reads the .env file in the project root.
If you only need the side effect of loading variables, you can import the autoload package with a blank identifier. It reads .env when the package is imported.
package main
import (
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
s3Bucket := os.Getenv("S3_BUCKET")
secretKey := os.Getenv("SECRET_KEY")
// now do something with s3 or whatever
}Load other files, or read values without changing the environment
You can pass file names to Load to read files other than .env, and you can pass several names at once. The README gives both forms as valid.
If you do not want godotenv to change the environment, use Read to get a map, Parse to read from an io.Reader, or Unmarshal to parse a string.
- godotenv.Load("somerandomfile") loads one named file.
- godotenv.Load("filenumberone.env", "filenumbertwo.env") loads several files.
- godotenv.Read() returns a map[string]string.
- godotenv.Parse(reader) reads from an io.Reader.
- godotenv.Unmarshal(content) parses a string.
var myEnv map[string]string
myEnv, err = godotenv.Read()
s3Bucket := myEnv["S3_BUCKET"]Control which values win and load per-environment files
Existing environment variables take precedence over values from files loaded later. This means a variable already set in your shell is not replaced by Load.
The README describes a convention for multiple environments: read an environment name from a variable such as FOO_ENV, defaulting to development, then load files in a set order. Use Overload only if you intend to replace existing variables, and the README advises caution.
- Load does not overwrite variables that already exist.
- Overload replaces existing variables. Use with caution.
env := os.Getenv("FOO_ENV")
if "" == env {
env = "development"
}
godotenv.Load() // The Original .env
godotenv.Load(".env." + env)
if "test" != env {
godotenv.Load(".env.local")
}
godotenv.Load(".env." + env + ".local")Run a command with variables from a file
When you installed the command-line tool, you can run any program with variables loaded from a .env file. Pass the file with -f. Without -f, the tool loads .env from the current directory.
By default the tool does not override existing environment variables. Add the -o flag to override them.
The README says the authors make no guarantees that the command-line tool works on Windows, though the project runs CI on Windows.
- -f sets the path to the env file.
- -o overrides existing environment variables.
godotenv -f /some/path/to/.env some_command with some argsWrite a map back to an env file
godotenv can write a map of values to a correctly formatted and escaped file, or return the same content as a string. This is useful when a tool needs to generate configuration.
- godotenv.Write(env, path) writes to a file.
- godotenv.Marshal(env) returns a string.
env, err := godotenv.Unmarshal("KEY=value")
err := godotenv.Write(env, "./.env")
content, err := godotenv.Marshal(env)What people use it for
- Keep database addresses and API keys for a Go service in a local .env file outside source code.
- Load different env files for development, test, and production using the README's naming convention.
- Read a remote or generated configuration string with Unmarshal and inspect its values as a map.
- Run a one-off Go or non-Go program with variables loaded from a chosen file using the godotenv command.
Frequently asked questions
Is godotenv free to use?
godotenv is released under the MIT licence, as stated in the project information. The README does not describe any paid tier.
What do I need to install godotenv?
You need Go installed. The README says Go 1.24 or newer is required only for the go get -tool form. The other install commands use go get or go install.
Does godotenv override existing environment variables?
No. The README says existing environment variables take precedence over values loaded later. The command-line tool also does not override by default, and the -o flag changes that.
Does godotenv work on Windows?
The README says the project has test coverage and CI for Windows, but the author makes no guarantees that the command-line tool works on Windows.
How is godotenv different from Ruby dotenv or Node.js dotenv?
godotenv is a Go port of Ruby's dotenv. The README notes a difference in key names: Ruby dotenv allows only letters, digits, underscores and dots, while Node's dotenv also allows hyphens, and godotenv matches the Node set since v1.4.0. Viper is also listed as a comparable project.
Can I load a file other than .env?
Yes. The README shows godotenv.Load with a single custom file name and with several file names.
New agent skills, repos and AI tools — every week
The best new skills and open-source projects, the fastest-growing repos, and one free prompt. Five minutes to read. Unsubscribe anytime.
Our verdict
godotenv suits Go developers who want local settings in a .env file, or who want to read such a file into a map without changing the environment. It is a small package with a fixed feature set, and the README says it is feature complete and not accepting new functionality. Projects not written in Go, or teams that need guaranteed Windows support for the command-line tool, should look at other options such as Viper or the Ruby and Node.js dotenv libraries.
Install options & downloads