Escaping the # character in .env file
Asked Answered
V

2

36

The secrete API key I want to store in my environment file for my express server is ignoring half of it as it contains a # symbol in the middle. I can't regenerate the key. And do not want it to be left unsequre

Viburnum answered 1/3, 2020 at 9:2 Comment(0)
M
28

i do not think it's because of the # symbol. It is only treated as signaling a comment when encountered as first chartacter in a line... you can try this yourself. create a .env file with the following content:

a=#b
c="#d"
#e=f

now run node -e 'console.log(require("dotenv").config())'

this will return:

{ parsed: { a: '#b', c: '#d' } }

Is there maybe a newline character somewhere?

Marpet answered 1/3, 2020 at 9:24 Comment(6)
Simply putting single quotes around the value did the trick. Thanks for your help.Viburnum
It is definitely the # symbol. I have the same problem. I have a PW and mid-way through it has a #. When I console log the environment variable in my server.js file it cuts the password right before hitting #.Dashpot
you are talking about an evironment variable this is about .env Files...Marpet
Yes, it is indeed the # symbol and needs single quotes or double quotes.Pentachlorophenol
I found that I had an issue when I wrapped env var in double quotes, but in single quotes it works fineStomachache
Could you update your answer to reflect the actual solution?Boughten
G
8

I encountered the same problem. In the .env file # is working as a breaking point because it is used for comments. To avoid this and use # in your environment variable you can consider your environment variable as a string.


For example, if your variable in your .env file is SECRET_CODE= my#code then change it to SECRET_CODE= 'my#code'. This solved the problem in my Express app

Gus answered 2/8, 2023 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.