DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Security Best Practices for ReactJS in Web App Development
  • How to Fix the OWASP Top 10 Vulnerability in Angular 18.1.1v
  • Unleashing the Power of WebAssembly to Herald a New Era in Web Development
  • Securing the Digital Frontline: Advanced Cybersecurity Strategies for Modern Web Development

Trending

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • A Guide to Developing Large Language Models Part 1: Pretraining
  • Rethinking Recruitment: A Journey Through Hiring Practices
  1. DZone
  2. Coding
  3. JavaScript
  4. Enhancing Security in JavaScript

Enhancing Security in JavaScript

Learn techniques for safeguards like input validation, output encoding, Content Security Policies (CSP), and secure coding practices.

By 
Aishwarya Murali user avatar
Aishwarya Murali
·
Feb. 13, 25 · Analysis
Likes (0)
Comment
Save
Tweet
Share
4.1K Views

Join the DZone community and get the full member experience.

Join For Free

Every programming language comes with its own set of security vulnerabilities, and JavaScript is no exception. Exploiting JavaScript vulnerabilities can lead to data manipulation, session hijacking, unauthorized data access, and more. Although commonly associated with client-side functionality, JavaScript security risks can also pose significant threats in server-side environments.

For any application, customer trust is highly important. Maintaining this trust requires safeguarding customer data and ensuring the security of applications. Fortunately, implementing proper safeguards can mitigate these risks and enhance the security of your application. 

In this article, we’ll explore some of the most common JavaScript security threats and discuss effective tools and strategies to protect your application from potential attacks.

Cross-Site Scripting

Cross-site scripting (XSS) is a security exploit that allows an attacker to inject malicious client-side code into a website. According to the Open Web Application Security Project (OWASP) Top 10 security vulnerabilities in 2021, XSS ranks as the third most common attack vector.

How to Mitigate XSS

Input Validation

Ensure that user input adheres to expected data types, formats, and ranges. Strip out or escape potentially harmful characters to prevent injection.

JavaScript
 
function validateInput(input) {
  return input.replace(/[^a-zA-Z0-9]/g, ''); // Allow only alphanumeric characters
}


Output Encoding

Convert special characters in output to their HTML entity equivalents to neutralize potentially malicious scripts before rendering.

JavaScript
 
function encodeHTML(input) {
  return input.replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/"/g, '"')
    .replace(/'/g, ''');
}


Clickjacking

Clickjacking is a deceptive attack that tricks users into clicking on an element that they do not intend to interact with. This technique involves embedding a legitimate website within a malicious one — often using an invisible or misleadingly positioned HTML <iframe> — to hijack user actions. As a result, attackers can steal login credentials, gain unauthorized permissions, or even trick users into unknowingly installing malware. 

One common way to achieve this is to use CSS to add an overlapping button that has opacity set to nearly 0. This tricks the user into clicking an unintended button or link.

How to Prevent Clickjacking

The X-Frame-Options instructs the browser whether the site can be embedded within an iframe. It has three options: 

  1. DENY – Prevents the page from being displayed in an iframe entirely
  2. SAMEORIGIN – Allows the page to be embedded only if the request originates from the same domain 
  3. ALLOW-FROM – Allows the page to be embedded only by a specific, trusted domain 

In Node.js you can use helmet to set these options like shown below:

JavaScript
 
const helmet = require("helmet");
const app = express();
app.use(
  helmet({
    xFrameOptions: { action: "sameorigin" },
  }),
);


An effective defense against clickjacking is implementing the Content Security Policy (CSP) header. CSP provides granular control over how and where content can be embedded, preventing unauthorized framing. 

To mitigate clickjacking risks, include the frame-ancestors directive in your CSP header. For example:

HTML
 
Content-Security-Policy: frame-ancestors 'self' https://www.example.org;


This policy ensures that the protected document can only be embedded by its own origin ('self') and explicitly allowed domains, such as example.org. It blocks all unauthorized attempts to frame the content, protecting users from clickjacking attacks.

Note: If frame-ancestors and X-Frame-Options are both set, then browsers that support frame-ancestors will ignore X-Frame-Options.

Cross-Site Request Forgery (CSRF)

CSRF (sometimes also called XSRF) exploits the trust a website has in a user's browser by making unauthorized requests on behalf of the user. Attackers trick users into executing actions without their knowledge, potentially leading to data breaches or unwanted transactions. A few examples are updating the victim's personal details, initiating a fund transfer from the victim's bank account, or even redirecting a package delivery to a different address. 

Let's look at a specific example of this. You are visiting your bank's website, and you've signed in. Say you get an email for a giveaway pretending to be your bank. The link takes you to a seemingly harmless webpage. Behind the scenes, a POST request gets triggered and sent off to the legitimate bank application.

PowerShell
 
curl --location --request POST 'https://acmebank.com/transfer?routing=852363&fromAccountNumber=123456789&toAccountNo=987654321' \
--header 'Cookie: session=acmebanksessionvalue'


On the acmebank.com application side, the “script” tag submits the form as soon as the user loads the page, without any user validation or the user even noticing what is happening, as shown below.

HTML
 
<html>
  <body>
    <form action="https://acmebank.com/transfer" method="POST">
      <input type="hidden" routing="852363" fromAccountNo="123456789" toAccountNo="987654321" amount="5000" />
    </form>
    <script>
  	window.addEventListener("DOMContentLoaded", () => {
    document.querySelector("form").submit();
  	});
	</script>
  </body>
</html>


The form above creates the following request to the actual application, acmebank. The request contains the legitimate user’s session cookie, but contains our bank account number! Because your session with your bank is still active, the transfer for the amount will go through if there is no other validation in place. 

How to Defend Against CSRF

Set the SameSite attribute set to Strict. This controls whether or not a cookie is sent with cross-site requests. 

  • Such session cookies should have a short lifetime. Require re-authentication for sensitive actions to mitigate risks.

Use CSRF session-unique tokens. This token can then be included within a form that is posted by the browser. For each request, the server compares the client-sent token against its stored value for the session. Use the library csrf-csrf to configure unique tokens.

Stealing Session Data

Session hijacking occurs when an attacker steals a user's session token, allowing them to impersonate the user and gain unauthorized access to their account.

How to Prevent Session Hijacking

Use Secure Cookies

Set the Secure and HttpOnly flags on session cookies to prevent unauthorized access. Setting the Secure attribute prevents the session cookie from being transmitted in clear text and only allows it to be transmitted over HTTPS connections. Setting the Http-Only attribute enforces the browser not to allow access to the cookie from the DOM which prevents client-side script-based attacks from accessing the sensitive data stored in those cookies.

Enable Multi-Factor Authentication (MFA)

Add an extra layer of security to verify users. This is a very common method that you will encounter in most secure applications. Easy integrations are available via providers such as Okta and Duo.

Implement Session Expiry

Automatically expire idle sessions to reduce attack windows. 

Coding Practices and Tools for High-Level Security

Vulnerability Scanning

A vulnerability scanner maintains the security of your application. Scanning your libraries, network, applications, and devices helps uncover weaknesses that attackers could exploit. Tools like Snyk and Sonarqube can be easily integrated into JavaScript codebases. These tools work in parallel with known lists of vulnerabilities maintained by OWASP. With seamless integration as part of the development process, these scanners provide developers and security teams with real-time and accurate visibility into code vulnerabilities and solutions to fix them.

Penetration Testing and Assessments

Developers can adopt penetration testing practices to actively probe and exploit potential vulnerabilities within an application. Ethical hackers simulate real-world attacks to assess the security posture of web applications by manipulating JavaScript code and user interactions. 

To accomplish this, developers can write customer JS code to simulate the scenarios, or they can utilize specialized penetration testing tools that leverage JavaScript to automate the process of scanning for common vulnerabilities like XSS, using OWASP ZAP. More information on penetration testing is available in OWASP's official guide. 

Web Application Firewall (WAF)

As applications grow, so does web traffic, increasing exposure to attacks. Implementing a Web Application Firewall (WAF) helps protect against malicious traffic by filtering and monitoring HTTP requests. This involves integrating with third-party WAF providers such as Cloudflare or AWS WAF. With WAF, you can define rules such as: 

  • Country or geographical location that requests originate from.
  • IP address, CIDR range and domain names that the requests originate from.
  • Limiting request lengths and query parameters to prevent injection attacks.
  • SQL code that is likely to be malicious. Attackers try to extract data from your database by embedding malicious SQL code in a web request. This is known as SQL injection.
  • Detecting and blocking embedded scripts that may be part of XSS attacks.

A WAF can also help mitigate Distributed Denial of Service (DDoS) attacks, ensuring application availability. 

Protect Data Integrity

Implementing robust data integrity measures is essential when storing or accessing secure information. Best practices include:

  • Enforcing strong password policies and encouraging password manager usage. In addition, encourage your users to use a password manager so that they can use more complex passwords and don't need to worry about remembering them (Use LastPass or 1Password). 
  • Protect against brute force attacks on login pages with rate limiting, account lockouts after a certain number of unsuccessful attempts, and CAPTCHA challenges.
  • Using HTTP headers such as:
    • HTTP Access-Control-Allow-Origin to control which origins can access resources.
    • HTTP X-Content-Type-Options to prevent MIME type security risks.
    • Subresource integrity (SRI) to ensure that resources from CDNs are untampered.

Conclusion

JavaScript security is an ongoing process that requires a proactive approach to safeguard applications from evolving threats. Implementing best practices such as input validation, CSP headers, secure session management, and vulnerability scanning can significantly reduce the risk of attacks like XSS, CSRF, and session hijacking. 

Additionally, utilizing security tools like WAFs, penetration testing, and MFA strengthens application resilience. Prioritizing security at every stage of development will allow developers to build robust, user-trustworthy applications that remain protected against modern cyber threats.

JavaScript security Cross Site Scripting

Opinions expressed by DZone contributors are their own.

Related

  • Security Best Practices for ReactJS in Web App Development
  • How to Fix the OWASP Top 10 Vulnerability in Angular 18.1.1v
  • Unleashing the Power of WebAssembly to Herald a New Era in Web Development
  • Securing the Digital Frontline: Advanced Cybersecurity Strategies for Modern Web Development

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!