Secure Front-End Development
Tags: webdev, cybersecurity, bestpractices, frontend
Published: 2024-06-14 18:09:33

---
title: Secure Front-End Development
published: true
date: 2024-04-10 13:48:33 UTC
tags: webdevelopment,cybersecurity,bestpractices,frontenddevelopment
canonical_url: https://medium.com/arctouch/secure-front-end-development-1179df166878
---

![](https://cdn-images-1.medium.com/max/1024/1*I6yXid2J5P31sQikB8d-vw.jpeg)
_html tag_

Front-end development is a crucial area for [web developers](https://arctouch.com/services/web-developers), standing out for its ability to create interactive and appealing user interfaces. This area encompasses a variety of technologies and tools, enabling developers to work in an agile and efficient way, implementing innovative functionalities that enhance the user experience. However, in addition to focusing on performance, accessibility, and usability, front-end developers must adopt secure development practices to ensure the protection and privacy of users.

### Attacks Originating from the Front-end

Certain types of cyber attacks can originate from the front-end if it is developed with some vulnerabilities. Gaining an understanding of how to enhance the security of an application necessitates a comprehension of some attacks that may stem from the front-end.

#### Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS) attacks are exploited through vulnerabilities in web applications, allowing external malicious code to be injected and executed in the context of the original application. This type of attack can have serious consequences, including the leakage of sensitive information, both from the system and from users interacting with the compromised site. This potential vulnerability puts the integrity and confidentiality of data at risk, making it essential to implement appropriate security measures to protect applications against this type of threat.

#### Cross-Site Request Forgery (CSRF)

Cross-Site Request Forgery (CSRF) attacks occur when authenticated users in a system are manipulated to perform unwanted actions without their knowledge. In these attacks, the malicious script is not directly inserted into the target system. Instead, these attacks exploit the active sessions of users, using cookies stored in the browser. This causes the system to mistake the malicious requests as legitimate, originating from the users themselves, leading to the execution of unauthorized actions.

#### Insecure Direct Object References (IDOR)

Insecure Direct Object References (IDOR) is a vulnerability that occurs when a web application exposes direct references to internal data. This allows attackers to access or manipulate data that they should not have access to, by exploiting these references. Essentially, IDOR violates access restrictions and permissions, enabling the attacker to view or modify information beyond their authorized permission scope.

### Fortifying the Front-end

Although the front-end alone cannot ensure the full security and integrity of a system, this article aims to explore ways in which the front-end can significantly contribute to the security of applications.

**CSP Configuration**

CSP (Content Security Policy) is a policy that, when configured on the front-end, informs the browser about the origin of the scripts it can execute, disregarding external scripts. Ideally, this configuration should be implemented both on the back-end and the front-end, but if that’s not possible, adding it on the front-end will already contribute to making users more secure when accessing your site.

Recognizing the need to ensure user security, since 2016, the W3C has been advising developers to implement these configurations. To set it up in React.js, you can add a meta tag in the index.html file.

```
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
```

**Using Cookies Securely**

I think many people, upon reading about the vulnerability in the use of cookies, might consider stopping their use. Therefore, I need to emphasize that one of the principles of secure development is not the sole use of one practice, but rather a combination of practices that involve all areas of the development process. However, focusing on cookies, using them securely requires that some configurations be made on the back-end (such as Anti-CSRF Tokens and adding the ‘samesite’ attribute to cookies).

On the front-end, as a way to ensure the security of the application, do not store sensitive data in cookies and use them only as a means to enhance the user experience, such as storing their usage preferences.

**Use of Local Storage**

Local storage is often used in day-to-day development, but the data stored in it and the way it is stored require some care, as it is possible to access the information through JavaScript. Therefore, avoid storing sensitive information and, if you need to store session tokens, opt for tokens that expire.

For example, assume you are working on the front-end of a sales system and will store the session token to ensure that the user has access to the sales area of the system. Within the system, to ensure that this user can have access, it will be necessary to present a credential (a token) whenever information is requested. Ideally, this token should be generated and managed by the backend and needs to contain an expiration date. This way, on the front necessary, this token will be sent to the back end to validate that it is still valid.

```
function verifyToken(apiUrl, key) {
    const token = localStorage.getItem(key);
    if (!token) {
        return;
    }

    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': token
        }
    })
    .then(response => {
        if (response.status === 498) {
            localStorage.removeItem(key);
            return;
        } else if(response.status === 200) {
            return token;
        } else {
            console.log('Received unexpected status:', response.status);
            return;
        }
    })
    .catch(error => {
        console.error(error);
    });
}
```

**Input Sanitization**

Input sanitization is a fundamental practice in the development of secure applications, especially in terms of front-end security. This process involves cleaning and validating data entered by users to prevent vulnerabilities, such as SQL injection or Cross-Site Scripting (XSS) attacks.

By sanitizing inputs, potentially malicious characters are removed or escaped, ensuring that only safe and correctly formatted data are processed by the application. This approach not only protects the system against malicious manipulations but also preserves the integrity of the data and maintains the reliability of the user interface, being a critical component for the security and stability of modern web applications.

### Tools to Help You Ensure Security

**DOMPurify**

DOMPurify plays a role in input security, which is an effective measure to mitigate the risks associated with the injection of malicious scripts, such as Cross-Site Scripting (XSS) attacks. This JavaScript library specializes in sanitizing HTML content, efficiently removing potentially dangerous elements and attributes.

By integrating DOMPurify into an application, developers can ensure that any content entered by users, such as comments or form entries, is cleansed of harmful scripts before being rendered in the browser. This not only protects the application but also enhances user safety, preventing the execution of malicious code and maintaining the integrity of the user interface.

![](https://cdn-images-1.medium.com/max/720/1*lAZ8KBWHFXppbWHw9dxrPA.png)
_DOMPurify library_

**NPM Audit**

The npm audit command is a built-in npm command that helps to check all dependencies installed in the project, to validate security vulnerabilities that have already been identified. When executed, it compares the versions of the packages used with a database of known security vulnerabilities and generates a detailed report. This report not only identifies vulnerable libraries but also presents alternatives to help with replacement and how to update to safer versions.

This functionality is extremely valuable for developers, as it helps to maintain the integrity and security of their applications, alerting them to potential risks and facilitating the management of vulnerable dependencies. Additionally, npm audit is a fundamental tool in continuous integration (CI) processes, contributing to the automation of vulnerability identification in the early stages of the development cycle.

![](https://cdn-images-1.medium.com/max/722/1*Q4KQPkJkudm52yRseBXCgw.png)
_npm audit documentation_

**Library for Anti-CSRF Tokens**

Depending on the project’s requirements, it may be necessary to store some information such as cookies on the server, and an alternative to do this securely, in addition to configuring the meta tag, is to use the csfr library.

![](https://cdn-images-1.medium.com/max/715/1*wYyqNnECiTr1PS5pBFiTMQ.png)
_CSFR library_

#### **Conclusion**

Front-end development security is an area where the adoption of safe practices becomes fundamental, integrating them from the beginning of the development process. Strategies such as the implementation of CSP, secure use of cookies, effective management of local storage, and sanitization of inputs are crucial steps for the protection of user data and the integrity of web applications.

With the introduction of AI tools in development, developers need to be even more attentive to the codes generated, adopting a critical approach in implementation to ensure security. This continuous process requires vigilance and constant updating, ensuring that applications not only impress with functionality and design but also stand out for their robust security.

At [ArcTouch](https://arctouch.com), we help companies create engaging and secure apps, websites, and connected experiences. See some of [our work](https://arctouch.com/portfolio).

**References**

- [Cross Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/)
- [Cross Site Request Forgery (CSRF)](https://owasp.org/www-community/attacks/csrf)
- [Insecure Direct Object Reference Prevention - OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html)
- [Content-Security-Policy (CSP) Header Quick Reference](https://content-security-policy.com/)
- [Content Security Policy Level 2](https://www.w3.org/TR/CSP2/)

* * *