Is it secure way to store private values in .env file?

hyojoon picture hyojoon · Feb 23, 2020 · Viewed 8.2k times · Source

I'm trying to build a node.js server with express framework, and I want to store a private key for admin APIs in my server.
I'm now using .env file to store those values, and in my routes, using that values by calling like process.env.ADMIN_KEY.

Question
Is it secure way to handle private datas? or there's another way better than this?

Answer

Martin Omander picture Martin Omander · Dec 16, 2020

It is more secure to store your secrets in a .env file than in the source code itself. But you can do one better. Here are the ways I've seen secrets managed, from least to most secure:

  1. Hard-code the secrets in the code.

    • Pros: None. Don't do this.
    • Cons: Your developers will see your production secrets as part of their regular work. Your secrets will be checked into source control. Both are security risks. Also, you have to modify the code to use it in different environments, like dev, test, and production.
  2. Put secrets in environment variables, loaded from a .env file.

    • Pros: Developers won't see your production secrets. You can use different secrets in dev, test, and production, without having to modify the code.
    • Cons: Malicious code can read your secrets. The bulk of your application's code is probably open-source libraries. Bad code may creep in without you knowing it.
  3. Put secrets in a dedicated secret manager, like Vault by HashiCorp or Secret Manager by Google Cloud.

    • Pros: It's harder for malicious code to read your secrets. You get auditing of who accessed secrets when. You can assign fine-grained roles for who updates secrets and who can read them. You can update and version your secrets.
    • Cons: It's additional technology that you have learn. It may be an additional piece of software that you need to set up and manage, unless it's included in the cloud platform you're using.

So the choice is really between items 2 and 3 above. Which one you pick will depend on how sensitive your secrets are and how much extra work it would be to use a dedicated secret manager. For example, if your project is running on Google Cloud Platform, the Secret Manager is just one API call away. It may be just as easy on the other major cloud platforms, but I don't have first-hand experience with them.