How to add comments to .env file?

I am using dotenv module to load environment variables from .env file.

.env:

# config
DAILY_REPORT_SCHEDULE='*/1 * * * *'
PORT=8080
NODE_ENV=development
DOTENV_DEBUG=true


# credentials
PROJECT_ID=shadowsocks-218808
KEY_FILE_NAME='/Users/ldu020/workspace/nodejs-gcp/.gcp/shadowsocks-218808-7f8e109f4089.json'

As you can see, I add two comments within .env file.

dotenv.js:

require('dotenv').config({ debug: process.env.DOTENV_DEBUG === 'true' });

dotenv give me debug messages:

[dotenv][DEBUG] did not match key and value when parsing line 1: # config
[dotenv][DEBUG] did not match key and value when parsing line 6:
[dotenv][DEBUG] did not match key and value when parsing line 7: # credentials
[dotenv][DEBUG] did not match key and value when parsing line 10:
[dotenv][DEBUG] did not match key and value when parsing line 11:

I know the reason why got these debug messages is I added two comments and some new line within .env file. dotenv does not parse .env file correctly.

How can I solve this?

51417 次浏览

In 2022 both separate line comments and inline comments are supported.

Line started with # symbol is a separate line comment. See the docs. Inlined # sign denotes the start of an inline comment (thanks to @reddisht to note this in comments).

For vlucas/phpdotenv the same situation.

Here is the example for both:

# This is the seprate comment line
NODE_ENV=stage
APP_VERSION=1.0.0 # This is an inline comment

The "#" (double quote wrapped hash symbol) is not treated as a comment even at line beginnig starting from v15.0.0 (thanks to @walkingbrad commented this below).

There are parsing peculiarities you may find good to knoww described in this docs section.

Yet do not forget that some packages like e.g. mrsteele/dotenv-webpack (at least v7.1.1) do not support inline comments and you can face your application's unexpected behaviour putting inline comments in your .env files.

Everything written in the same code line right of # or ; is comments.

As of 2022-04-17, both comment lines and inline comments are available. Just use #.

Shamelessly copied from https://github.com/motdotla/dotenv#comments:

# Comment
SECRET_KEY=YOURSECRETKEYGOESHERE # Comment
SECRET_HASH="something-with-a-#-hash"

You can add a comment in .env by starting a line with a hash (#) symbol. E.g.

# host value
DB_HOST=host
# username
DB_USER=admin
# secure password
DB_PASS=pass

As of 13 Aug 2022 7:20 am UTC (Because Node, Angular, javascript etc. keep changing often) this is the status:

You can use # for comments.

# MY_TEMPORARY_VARIABLE = 'Some value'

But remember, this feature is still in primitive stage as it will not accept comment in same line. Thus:

MY_TEMPORARY_VARIABLE = 'Some value' # This is comment

In this case

let myVar = process.env.MY_TEMPORARY_VARIABLE;

myVar will hold value:

'Some value # This is comment'

You are welcome!