Angular 9, Heroku and Node.js: Encrypt and Decrypt data with Crypto-js
Encrypt / Decrypt apiKey with Crypto-js
This is primarily for an existing angular app but this may be applicable for other use cases regarding encrypting data via node.js / express server.
If you have a scenario in where you might need to send a private apiKey to the client side of an Angular app this is an example of how it can be done using Crypto-js. In this example I am fetching a private config variable from a heroku app and sending the apiKey
to the client-side. Since I don’t want the the apiKey exposed in the dev tools Network I must first encrypt the apiKey
. For Heroku this app uses a node.js / express server file app.js
.
- Create a new file in the root of the app
touch app.js
- To set up a node.js express server run
npm i express http path --save
//app.js const express = require('express');
const http = require('http');
const path = require('path');
const app = express();app.use(express.static(path.join(__dirname, 'dist')));//SPECIFY NG-BUILD PATH
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'))
});//HEROKU PORT
const port = process.env.PORT || '3001';
app.set('port', port);const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
- Run
ng build
to build the app in the dist directory.dist/index.html
- Run
node app.js
to serve the app athttp://localhost:3001
. - The
Procfile
in this app’s root specifies the server for heroku to use.
//Procfileweb: node app.js
- This
"main": "app.js"
line in package.json specifies how to tell heroku to look forapp.js
. - Before pushing to github, before heroku deploy set Config Variables.
Adding the environment variable apiKey for the api. I didn’t want to share my apiKey
headers information in my github repository so I added my apiKey
to my Config Variables for heroku to use. I stored the apiKey
in my heroku app by going to the app settings in my heroku dashboard. Click on Config Variables and add the key (name) and value (apiKey) there. It will be secured privately away from view. You can call it to the client side by adding this code to the app.js
file. I called my env TOKEN
and made the value the apiKey
.
Before I send my TOKEN
to the client-side I want to encrypt it by using the Crypto-js module.
- To encrypt the
apiKey
(TOKEN) before sending to the client-side runnpm i crypto-js --save
//app.js const express = require('express');
const http = require('http');
const path = require('path');
const CryptoJS = require("crypto-js");
const app = express();let TOKEN = '';
let ciphertext = null;app.use(express.static(path.join(__dirname, 'dist')));//SEND API KEY TO FRONT-END APP.COMPONENT.TS
app.get('/heroku-env', function(req, res){
ciphertext = CryptoJS.AES.encrypt(process.env.TOKEN, 'myPassword').toString();
TOKEN = ciphertext;
res.json(TOKEN);
});//SPECIFY NG-BUILD PATH
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'))
});//HEROKU PORT
const port = process.env.PORT || '3001';
app.set('port', port);const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
- Encrypt the
apiKey
(TOKEN) with Crypto-js using a made up password as the right param. app.get '/heroku-env'
will send the encrypted token when called from the client-side.- Get the
apiKey
sent from the server to the client-side using Http.this.http.get('/heroku-env')
- Decrypt the
apiKey
(TOKEN) when fetched from server by importing Crypto-js using the same password param.
The apiKey
will be sent as an encrypted string. The res
(response) from app.js
will then need to be decrypted before adding to httpHeaders to allow authentication of an api request. Each api request may be a little different but this example should get you close to how you would make a proper api request.
//app.component.ts import { Component, Inject, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import * as CryptoJS from 'crypto-js';@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})export class AppComponent implements OnInit { constructor(private http: Http) {} getEnv() {
console.log("trying to get heroku env...");
this.http.get('/heroku-env')
.subscribe(res => {
let bytes = CryptoJS.AES.decrypt(res, 'myPassword');
let key = bytes.toString(CryptoJS.enc.Utf8);
headers = new HttpHeaders().set("Authorization", "Basic " + btoa(key + ":" + 'MYAPIFEED'));
});
} ngOnInit() {
this.getEnv();
}
}
Deploy to Heroku
If you are trying to deploy to heroku for the first time and your private keys are hidden proceed with the following steps. After you git push
to your github repo follow the steps below. Assuming you have a heroku account and installed the heroku toolbelt.
- run
heroku log in
- run
heroku create name-of-app
- run
git push heroku master
- If deploy is successful run
heroku open
If there were problems during deploy and you are trying this from scratch here are some requirements heroku needs to deploy.
- Have
@angular/cli
and@angular/compiler-cli
listed under dependencies inpackage.json
. - Add
"postinstall": "ng build"
to the package.json’s"scripts"
object.
//package.json"main": "app.js",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"postinstall": "ng build"
},
"engines": {
"node": "~10.16.2",
"npm": "~6.13.7"
},
"dependencies": {
... "@angular/cli": "9.0.1",
"@angular/compiler-cli": "^9.0.0", ...
To test that the encryption is working after deploying to heroku open your app and check the network tab in chrome dev tools. Search for the request heroku-env
and click on the response tab. You should see an encrypted string.