node.jsdotenv

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?


Solution

  • Since 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 separate 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 beginning starting from v15.0.0 (thanks to @walkingbrad commented this below).

    There are parsing peculiarities you may find good to know 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.