How to Make Your Nodejs Backend Secure

Written by haykoyaghubyan | Published 2020/01/08
Tech Story Tags: nodejs | express | security-factors | api-security | node-backend-development | secure-software-development | programming | javascript

TLDR How to Make Your Nodejs Backend Secure: How to make your Node.js back-end secure. Hackers can use code injection techniques that might destroy your database. Validate every form in front-end before allowing users to send that data to the back end. Logging is the opportunity for tracking your site visitors to see what action and where they take? How do visitors interact with your site? It also provides additional details about every visitor. Use Express Validator in your.js controllers for validating each submitted field.via the TL;DR App

As you know these days security becomes more and more important for all kind of startups. As a startup owner, you should pay attention to your web app’s security in the first place. Remember that users are trusting their information to you and you should care about their data professionally otherwise if someone hacks your web app and steals the data you will fail and lose your customers.
It doesn’t matter you are building a saas business or a crowd-sourcing platform.
It doesn’t matter what kind of data are you collecting.
You have to care about the security of your platform. We are going to cover back-end security in this tutorial. We will use Node.js with Express for powering our API.
1. Injections
One of the most popular attacks is SQL injection. The SQL injection is a code injection technique that might destroy your database. The hacker can just submit anyone of these snippets and crash your DB.
' ; DROP TABLE customers; --
this line will remove the complete table of your customers.
' OR 1=1 --
This line can be submitted through the password field and get access to the user data.
So how can you overcome SQL injection attacks in Node.js?
It’s recommended to use ORM in your back-end for working with Databases, for example, Knex.js. However, keep in mind that SQL injection is not the only injection type that hackers can use. Injection means mixing external code by your code by submitting those bad code lines in the forms of your site. The best way to overcome any injection attack is by doing these steps.
  1. Validate each field in your DB 
  2. Use Express Validator in your Node.js controllers for validating each submitted field
  3. Validate every form in front-end before allowing users to send that data to the back-end. It doesn’t matter you are using Angular, React or Vue.js. They have a fantastic and well-explained solution for this.
2. Checking 3rd party libraries carefully
Remember that all 3rd party libraries are open source and are uploaded by other developers. What if anybody creates that package with vulnerability for harming later? It’s recommended to check every package for available vulnerabilities. We used a package called NSP but NPM acquired it in 2018 so now it’s part of NPM. You can also use Snyk.
run
npm install -g snyk
Once installed you will need to authenticate with your Snyk account and then test.
You might also notice that when you install npm packages it tells you about vulnerabilities. Don’t ignore it! Just run
npm audit fix
that will solve the most of them.
3. Logging
Logging is the opportunity for tracking your site visitors to see what action and where they take? How do visitors interact with your site? It also provides additional details about every visitor. In other words, if someone is trying to do a strange thing in your website you can get more information about that person by checking the logs.
Luckily for us, there are 2 great packages that help to solve this problem in Node.js so easily. You can use either Winston or Morgan. I love Morgan more and used it several times in previous projects. Let’s see how does it work?
Firstly we need to install it:
npm install morgan
It’s just a middleware and we need to include this line in the index.js:
app.use(morgan('combined'));
There are other options that work well too but the combined option provides you a lot of information.
4. Keep secure your environment variables
You might use email services like Sendgrid, you might accept payments by using Stripe or Paypal. You might use Twillio for SMS verifications. For each of such a service provider, you are using an API key that must be kept in a secure place. The best practice for this is keeping all these API key values in one separate file called .env. You can assign those values into variables then can use in the needed controller functions. I will recommend using dotenv library. Let’s install it:
npm install dotenv
Then when you use environment variable from .env file let’s assume it’s called stripe_key then you just need to use it inside your controller like this:
process.env.stripe_key
That’s it. 
One more note: Don’t forget to include .env file inside .gitignore if you are going to push that code into the Github publicly and also write in the documentation what kind of APIs are required for running the project so other users can create accounts on those platforms and get their own keys.
5. Setting up secure headers
Having secure headers is also very important. It helps you to protect your API from XSS attacks. Here is where Helmet comes for help. It’s another middleware that you should install and include in the index.js of your project.
6. Setting up access control for your API
It’s very important to control the access of your API otherwise anybody can access it and do whatever they want. That’s why you need to use Cors library for protecting your API. Here is how it works:
As a middleware you should configure it inside index.js. It will look like this:
const whitelist = ['http://example1.com', 'http://example2.com']
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.use(cors(corsOptions));
As you see you can store domain names for which you give permission. You can check official documentation for its complete implementation.
7. Database management
Another important thing is hashing passwords in your DB so nobody can get the real values of stored passwords. Of course, there might be another field that you might want to hash but the most common field is a password field. 
The most popular libraries are these 2 ones: 
8. Authentication management
Authentication management is one of the most important factors for keeping your site secure. It helps you to manage users' seasons and understand what kind of data and what kind of pages give them access? These days the most popular solution is using JWT (JSON Web Tokens). Since it’s a large and different topic we will not cover its integration in this tutorial but there are many tutorials about JWT implementation that you can find on the internet.
9. Use HHTPS
These days SSL certificates become a very popular and essential thing for running an online business. There were many certificate authorities who sold these certificates but there are 2 free options that you can use:
Cloudflare is well known as CDN but it also converts your site into HTTPS as well as protects it from DDoS attacks.
Conclusion
Making your website secure is a regular process and you should care about it regularly for finding new vulnerabilities and fixing them.

Published by HackerNoon on 2020/01/08