Jwqq
Jwqq

Reputation: 1097

How to read environment variable in Nodejs?

I am trying to read a environment file through docker compose.

My problem is my code only read the first line of the variable value.

My test.env

NODE_ENV=development
## Not the actual key ##
RSA_PUBLIC=-----BEGIN PUBLIC KEY-----
CIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyRaUPVDIx3e1d/qadcNc
D5TfmAfjCKlTajQPEitF8tNtQKRQc9yZqJjkNwtvctlxmkBmfot5dPqW/nAZhfse
AAY5AKnAPAHrOLrzrGWvXE1NkjuONZq9cTqWludyZp7jH0md1q/D7shZMwL2hEee
gaaM5CWH7nIZ6CASDA9K46NJYyoXw4/sZsUtuuKbUP3W1LlJcaBFIpRRKkv2dEdd
ddqN8yHjkjKNtHi0UtRCjxA6dOuUdMvTiTHiycGwoC6sap0THF4lWHBZb/GXFaeD
adce7iDq5bhbMNT3YfXHlq3MMMJSCJltnVS7DArij/Xf6vF/6chvlI4S9iIZNped
FEEDAAEE
-----END PUBLIC KEY-----

My docker-compose

web:
    build: .   
    env_file:
      - test.env
    //more

I was able to read NODE_ENV in my app.js file with

console.log(process.env.NODE_ENV) ==> output development

but console.log(process.env.RSA_PUBLIC) ==> only output -----BEGIN PUBLIC KEY-----

which is the first line of the key.

and make my jwt token validation failed with

PEM_read_bio_PUBKEY failed

I am not sure how to fix this. Can anyone help me about it? Thanks a lot!

Upvotes: 0

Views: 996

Answers (2)

twg
twg

Reputation: 1105

Two thoughts:

  1. How do you store the variable? Do you use the process.env directly, or something like dotenv?

  2. Did you try storing without the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" lines?

Upvotes: 1

ZeroCho
ZeroCho

Reputation: 1360

The solution for this might differ by linebreak style of your OS, but I solved this issue by replacing linebreak with \n(which makes your key a single line string), and then read it on server by replacing \n with \n

process.env.RSA_PUBLIC.replace(/\\n/g, '\n')

Upvotes: 1

Related Questions