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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...