Securing Node.js Applications: 3 Flexible Approaches
Express.js provides a powerful solution for building backend web apps, but falls short on security. When you build a web application, you need adequate security measures to protect your users’ data.
Fortunately, there are methods you can use to improve the security of your Express.js applications. These tips all help to strengthen the security of your applications in various ways.
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 folder to it on your terminal.
mkdir express-project
cd express-project
Then create one package.json file in the root directory.
npm init -y
Go ahead and install Express.js.
npm install express
Finally, make one server.js file in the root of your project folder and add the following code to set up a simple web server.
const express = require("express")
const app = express()
const PORT = process.env.PORT || 5000app.get("https://www.makeuseof.com/", (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 are now ready to explore some of the measures you can use to secure your Express.js application.
1. Secure Express.js applications with a helmet
Helmet is a Node.js middleware that helps secure apps on the server side by setting various HTTP security headers. These headers provide essential defenses against common backend security vulnerabilities such as cross-site scripting (XSS), cross-site request forgery (CSRF), and many more.
Express.js does not configure HTTP security headers by default, creating a potential vulnerability that exposes potentially sensitive headers. Using this information, malicious actors may be able to gain unauthorized access or otherwise disrupt your app.
Helm acts as a vital shield, ensuring that the application’s HTTP responses take the necessary security measures, greatly reducing the potential attack surface.
Exploring the security of Express.js applications without a helmet
Examine the application headers while the server is running. Go ahead and submit HTTP requests to the API using Postman or any other client that shows response headers. Most browsers include a set of developer tools that allow you to do this.
When you send requests to the home endpoint, you see similar results in the Headers part of the answer within Postman.
watch the X powered by header. Typically, backend technologies use this header to indicate the framework or other software that powers the web application. Usually you need the X powered by header in a production environment.
Doing so will 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 use the online tool Security Headers. This app is specially designed to evaluate the security configuration of HTTP headers for client-side and server-side applications.
First you need to make your local Express.js server accessible from the internet. There are two possible approaches to achieve this: deploying your Express.js application to a cloud server or using ngrok.
To use it, download the ngrok zip file, extract the executable file 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:
Copy the provided forwarding URL and paste it in the Security headlinesinput box and click on it Scan knob.
Once the security assessment is complete, you will receive a similar report.
Based on the report, it is clear that the Express.js server got a bad one F figure. This low score is a result of the lack of critical HTTP security headers in the server configuration. Their absence leaves the server vulnerable to potential security risks.
Integrate Helm into 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, turn up the development server, copy the forwarding link from ngrok’s terminal and paste it into it Security Head input field to rescan the local server. Once the new scan is complete, you should see results similar to this:
After the Helmet integration, Express.js includes several critical security headers in the HTTP response. This substantial improvement caused the Express.js application to transition to a a figure.
While Helmet is not a foolproof solution, it greatly improves the overall security of your Express.js application.
2. Secure Express.js applications with 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 clean user input. By defining validation schemes using Joi, you can specify the expected structure, data types, and constraints for incoming data.
Joi validates the input against the defined schema and ensures that it meets the specified criteria. This helps 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.
- Install Joy.
npm install joi
- Import Joi into your server.js file.
const Joi = require('joi');
- Create a JOI data validation scheme 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()
}); - Validate all incoming data against the defined schema.
const { error, value } = schema.validate(req.body);
if (error) {
return res.status(400).json({ error: error.details[0].message });
}
By implementing these steps, you can take advantage of Joi’s input validation capabilities to secure your Express.js applications. This ensures that the incoming data conforms to defined restrictions, preventing potential data tampering security risks.
3. Secure 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.
Follow these steps to secure Express.js applications using CORS:
- Install the CORS package.
npm install cors
- Requires and uses 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.
Secure server-side applications with ease
You can use one or more of these critical measures to improve the security of your Express.js applications.
While there are many measures and approaches available to protect your server-side applications, the most important thing to prioritize is security throughout the development lifecycle. This is a task that starts at the design stage and must continue through implementation.