NodeJS Secure Environment Variables with Google Key Management Service
Introduction
When developing applications, using environment variables is essential. They help configure values for different environments like development, staging, and production. Some environment variables, such as API keys, database connections, or passwords, are sensitive and need to be kept secure. If you're using Google Cloud, their Key Management Service (KMS) can help you manage keys, and allows you to encrypt and decrypt values using those keys.
Prerequisites
Before we proceed, make sure you have:
- A Google Cloud account with permissions to use KMS.
- Google Cloud CLI installed.
- Basic knowledge of NodeJS. You can refer to this guide to set up a NodeJS TypeScript project, which will be used in this tutorial.
Key Management Service
KMS works with key rings, which hold multiple keys. You use these keys to encrypt and decrypt string values or file data.
Be cautious: if a key is deleted, any data encrypted with it can't be decrypted anymore.
To create a key ring, execute the following command:
Then create a key based on the keyring.
You can check the keyring and key that were created by using a command or by visiting the Google Cloud Console.
Deploying with NodeJS
Once you've successfully set up your NodeJS Typescript project, install the following package:
Use the following code block to interact with Google KMS.
I use `process.env.GCP_USERNAME` and `process.env.GCP_PASSWORD` defined in the `.env` file like this
The values for GCP_USERNAME and GCP_PASSWORD are encrypted in base64 based on the key created above. Therefore, you cannot use the usual method to decrypt these values.
To encrypt a value to base64, use the following command:
After obtaining the value, replace it in your .env file accordingly.
The result of executing the code will be as follows:
Comments
Post a Comment