Skip to main content

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 date 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 at http://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 for app.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 apiKeyheaders 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 run npm 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();
   }
}
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.
  1. run heroku log in
  2. run heroku create name-of-app
  3. run git push heroku master
  4. 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.
  1. Have @angular/cli and @angular/compiler-cli listed under dependencies in package.json.
  2. 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.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...