MakeUseOf logo

How to Secure Node.js Applications: 3 Flexible Approaches

Padlock over a background of code
Image Credit: madartzgraphics/Pixabay
No attribution Required
URL: pixabay.com/illustrations/hacker-hacking-cyber-security-hack-1944688/

Gichuhi Wachira holds a Bachelor of Science degree in Computer Science and works as a front-end developer and technical writer with over two years of writing experience.
He writes about various web and cloud technologies, as well as programming concepts, for MUO. Besides writing or tinkering with new technologies, he spends his time outdoors.

Sign in to your MakeUseOf account

Express.js provides a performant solution for building backend web apps, but it falls short on security. When you’re building a web application, you need adequate security measures to protect your users’ data.

Fortunately, there are methods you can take to enhance the security of your Express.js applications. These tips will all help bolster the security of your applications using different approaches.

Set Up an Express.js Application

Start by setting up a demo Express.js web server using npm, the Node Package Manager. Create a project folder locally and change the directory to it on your terminal.

mkdir express-project
cd express-project

Next, create a package.json file in the root directory.

npm init -y

Go ahead and install Express.js.

npm install express

Finally, create a server.js file in the root directory of your project folder, and add the following code to set up a basic web server.

const express = require("express")
const app = express()
const PORT = process.env.PORT || 5000
app.get("/", (req, res) => {
 res.json("Hello, World!")
})
app.listen(PORT, () => {
 console.log(`Starting server on http://localhost:${PORT}`)
})

Start the server with this command:

node server.js

You’re now ready to explore some of the measures you can use to secure your Express.js application.

1. Securing Express.js Applications Using Helmet

Helmet is a Node.js middleware that helps secure server-side apps by setting various HTTP security headers. These headers provide essential defense mechanisms against common backend security vulnerabilities, such as cross-site scripting (XSS), cross-site request forgery (CSRF), and many more.

[画像:A man sitting at a desk typing on a laptop with code on the screen.]
Image credit: Danial Igdery/ Unsplash -- No attribution required - https://unsplash.com/photos/FCHlYvR5gJI

Express.js does not configure HTTP security headers by default, leaving a potential security flaw that exposes potentially sensitive headers. Using this information, malicious actors may be able to gain unauthorized access or otherwise disrupt your app.

Helmet acts as a vital shield, ensuring that the application's HTTP responses adopt necessary security measures, significantly reducing the potential attack surface.

Exploring the Security of Express.js Applications Without Helmet

With the server running, examine the application's headers. Go ahead and make HTTP requests to the API using Postman or any other client that shows response headers. Most browsers include a set of developer tools that will let you do so.

When you send requests to the home endpoint, you should observe similar results in the Headers section of the response within Postman.

[画像:HTTP API response default headers' data on Postman API client.]
Image credit: Gichuhi Wachira
No attribution required

Notice the X-Powered-By header. Typically, backend technologies use this header to indicate the framework or other software that powers the web application. You should usually remove the X-Powered-By header in a production environment.

By doing so, you’ll prevent potential attackers from obtaining valuable information that they could use to exploit known vulnerabilities associated with your technology stack.

Test the Security Configuration of the Express.js Server

To assess the security status of your applications, we'll use the Security Headers online tool. This app is specifically designed to evaluate the security configuration of HTTP headers for client-side, as well as, server-side applications.

First, you need to make your local Express.js server accessible over the Internet. There are two possible approaches to achieve this: deploying your Express.js application to a cloud server or utilizing ngrok.

To use it, download the ngrok zip file, extract the executable, and launch the application. Then, run the following command to host your local Express.js server with ngrok.

ngrok http 5000

ngrok will output some brief information that looks like this:

[画像:ngrok web server information on a terminal window.]
Image credit: Gichuhi Wachira
No attribution required

Copy the provided forwarding URL and paste it into the Security Headers' input box, and click on the Scan button.

[画像:security headers online tool forwarding URL input field]
Image credit: Gichuhi Wachira
No attribution required

Once the security evaluation is complete, you should receive a similar report.

[画像:A failed Security Header HTTP security headers evaluation report]
Image credit: Gichuhi Wachira
No attribution required

Based on the report, it is evident that the Express.js server received a poor F grade. This low grade is a result of the absence of essential HTTP security headers in the server's configuration—their absence leaves the server vulnerable to potential security risks.

Integrate Helmet in the Express.js Application

Now, go ahead and integrate Helmet into your Express.js application. Run the command below to install the dependency.

npm install helmet

Update your server.js file and import Helmet.

const helmet = require("helmet")

Now, add Helmet to your Express.js application.

app.use(helmet())

Finally, spin up the development server, copy the forwarding link from ngrok's terminal, and paste it into the Security Header's input field to rescan the local server. Once the rescan is complete, you should see similar results to these:

[画像:A successful Security Headers HTTP security headers evaluation report]
Image credit: Gichuhi Wachira
No attribution required

After integrating Helmet, Express.js includes several essential security headers in the HTTP response. This substantial improvement caused the Express.js application to transition to an A grade.

While Helmet is not a foolproof solution, it significantly enhances the overall security of your Express.js application.

2. Securing Express.js Applications Using Joi, an Input Validation Library

Joi is an input validation library that helps secure Express.js apps by providing a convenient way to validate and sanitize user input. By defining validation schemas using Joi, you can specify the expected structure, data types, and constraints for incoming data.

Joi validates the input against the defined schema, ensuring that it meets the specified criteria. This helps to prevent common security vulnerabilities such as data injection, cross-site scripting (XSS), and other data manipulation attacks.

Follow these steps to integrate Joi into your application.

  1. Install Joi.
    npm install joi
  2. Import Joi in your server.js file.
    const Joi = require('joi');
  3. Create a Joi data validation schema that defines the expected structure and any constraints for the input data.
    const schema = Joi.object({
     email: Joi.string().email().required(),
     password: Joi.string().min(5).max(16).required()
    });
  4. Validate all the incoming data using the defined schema.
    const { error, value } = schema.validate(req.body);
    if (error) {
     // Handle validation error
     // For example, return an error response
     return res.status(400).json({ error: error.details[0].message });
    }

By implementing these steps, you can leverage Joi’s input validation capabilities to secure your Express.js applications. This will ensure the incoming data meets defined constraints, preventing potential data manipulation security threats.

3. Securing Express.js Applications Using the CORS Mechanism

Cross-Origin Resource Sharing (CORS) is a mechanism that web servers use to manage which origins—clients or other server-side applications—can access their protected resources. This mechanism helps protect against unauthorized cross-origin requests, preventing issues such as cross-site scripting (XSS) attacks.

To secure Express.js applications using the CORS, follow these steps:

  1. Install the CORS package.
    npm install cors
  2. Require and use CORS middleware in the server.js file.
    const cors = require('cors');
    app.use(cors());

By integrating the CORS middleware into your Express.js application, you enable Cross-Origin Resource Sharing. This ensures that you mitigate potential security risks related to cross-origin requests.

Securing Server-Side Applications With Ease

You can use one or more of these essential measures to enhance the security of your Express.js applications.

While there are many measures and approaches available to protect your server-side applications, the key takeaway is that you should prioritize security throughout the entire development lifecycle. This is a task that begins at the design phase and should continue right the way through to deployment.

AltStyle によって変換されたページ (->オリジナル) /