7 security tips for your React application. 🔐
Tags: react, javascript, webdev, security
Published: 2020-07-10 17:31:42

It happens that in your organisation the very first React application is built with months of dedication, great developers coding with ridiculous decency which is reflected in their [clean code](https://medium.com/mindorks/how-to-write-clean-code-lessons-learnt-from-the-clean-code-robert-c-martin-9ffc7aef870c) practices, the performance index is superb and yes, its user experience is unmatched! The time has come. You've just finished all the major deployment, DevOps stuff and crazy testing. You're about to deploy this wonderful application which will definitely help grow your business a lot. _You deploy, you fail and then you reflect..._

None of these performance indexes, UX reviews, testing etc matters unless your application is secure. In today's world, data is the most precious gem you can find on Earth. ([no, I'm not joking!](https://www.iotforall.com/data-worlds-most-precious-resource/)) Your entire business may collapse in a drift if your application is insecure or one 12-year-old hacker jailbreaks your code to sell for bad stuff. Hence, it's highly important that every application **must** be secure first. As you're a React dev, here are some of the common tips you'll find around to safeguard that JSX code.

![Lock GIF](https://media.giphy.com/media/111Z8z6B8226vm/giphy.gif)
<figcaption>Eh, don't be that landlord of your React app...</figcaption>

---

## 1️⃣ Secure your HTTP authentication

If your application has some authentication feature where users log in or create an account, you need to make sure it's secure because usually the client-side authentication and authorization is the one which is exposed to multiple security flaws which may damage these protocols within the app.

Most prominently, you would've used one of the following methods to add authentication:

- [JSON Web Token (JWT)](https://jwt.io/)
- [OAuth](https://oauth.net/2/)
- [AuthO](https://auth0.com/)
- [React Router](https://reactrouter.com/)
- [PassportJs](http://www.passportjs.org/)

Let's take a look at how you can safeguard with JWT:

<center>**✔ Dos and Don'ts ❌**</center>

❌ **DON'T** store your JWT tokens on [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). Someone can easily use the browser's dev tools console and write this to get this token <em>very</em> easily:

```js
console.log(localStorage.getItem('token'))
```
They can now make use of this token to send them to a different location where they may be collecting them! That's bad for both you and your users.

✔ **DO** move your tokens from `localStorage` to a [_HTTP cookie_](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies).

✔ Else, **DO** move your tokens to your [_React app's state_](https://kentcdodds.com/blog/application-state-management-with-react).

❌ **DON'T** keep the secret keys that go into signing your tokens in the _browser_. Anyone who visits your website can see the different data, cookies, tokens etc. If you're sending the secret keys you should know that they can be used to sign some new tokens!

✔ **DO** keep them on your _backend_. Always _sign and verify_ these keys on the backend.

✔ **DO** use _long and unguessable_ secrets. Just like when you create an account and the password field tells you to make a strong and long password, same goes on with these JWT secrets.

❌ **DON'T** decode the token on _client-side_. Especially the access tokens. Generally, these access tokens are meant for the APIs powering the application.

✔ **DO** keep an `expiresAt` key on your `localStorage`. [Here's](https://www.sohamkamani.com/blog/javascript-localstorage-with-ttl-expiry/) a simple method on how you can add an expiry time for reference.

✔ **DO** keep your token payload _small_. The bigger the payload > the bigger the size of your token > the larger the request when they hit the endpoint > more bandwidth power from your users > the less performant your app.

✔ **DO** make sure you're using _HTTPS_ and NOT HTTP under any circumstance. This will make sure your web app has a valid certificate and it sends the data over this secure [SSL](https://www.cloudflare.com/learning/ssl/what-is-an-ssl-certificate/) connection.

I recently came across [this comment by Warren](https://dev.to/wparad/comment/11om4), it's insightful.

## 2️⃣ Secure against DDoS attacks

Typically this security vulnerability occurs when the app isn't secure enough or it has some loopholes in masking the IPs of services. Due to this, it can't interact with the server causing some services to stop. Here are some ways to stop this:

1. **Rate limiting** on APIs: you just limit the number of requests to a given IP from a specific source. There's an entire library if you're using [Axios](https://www.npmjs.com/package/axios) called [axios-rate-limit](https://www.npmjs.com/package/axios-rate-limit).

2. Add **app-level restrictions** to the API.

3. Make calls on the server and **NOT** on the client-side.

4. Add some **tests** to secure the app layer. Here's a good article on the same:

{% medium https://medium.com/dailyjs/exploiting-script-injection-flaws-in-reactjs-883fb1fe36c1 %}

## 3️⃣ Secure against Cross-Site Scripting (XSS) attacks

XSS is quite risky as the injected code from the attacker will be executed as a legitimate app code, giving the attacker full control over the application running in the user’s browser. It can look as cute as this:

```js
I'm just an innocent code!<script>alert("Unless I'm not 😈")</script>
```
And here's the same code with some protection from XSS:

```js
I'm just an innocent code!&lt;script&gt;alert("Unless I'm not 😈")&lt;/script&gt;
```
As you might know, `&lt;` and `&lt;` are interpreted as `<` and `>` respectively so the browser will not confuse the data for code this time. Some more ways to shield are:

1. Using the **[`createElement()`](https://reactjs.org/docs/react-api.html#createelement)** API.

2. Using **[JSX auto escape](https://reactjs.org/docs/jsx-in-depth.html#string-literals)** feature.

3. Using **[`dangerouslySetInnerHTML`](https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml)** to set HTML directly from React instead of using the error-prone [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML). Chekout the following thread:

{% stackoverflow 37337289 %}

## 4️⃣ Secure against Cross-Site Request Forgery (CSRF) attacks

[CSRF attacks](https://owasp.org/www-community/attacks/csrf) take place through unauthorized cookies placed within your app by the attacker or by some unintended cookies. It forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. Get some important points to not allow it to happen:

1. **Use those JWT tokens** for session management.

2. Make sure your application reads **only the stored CSRF tokens**.

3. Generate **relevant token headers** by making an authenticated request to the server. 

## 5️⃣ Secure against broken authentication

You enter your authentication details and boom...the app crashes leading to exploitation of credential data. Make sure you have the following stuff ready to not allow it:

1. Use **[multi-factor](https://scotch.io/tutorials/multifactor-authentication-in-your-react-apps)** and **[2-step authorisation](https://hackernoon.com/how-to-implement-google-authenticator-two-factor-auth-in-javascript-091wy3vh3)**.

2. Use **cloud-based authentication** for secure access. Here's an article on [Authentication for React apps using AWS Amplify and Cognito](https://blog.logrocket.com/authentication-react-apps-aws-amplify-cognito/).


## 6️⃣ Secure against libraries and components

There's always a risk involved whenever you use a third-party library, modules, or APIs in your React app. Sure, they do help us a lot in the rapid development of features but who knows their own set of security flaws might destroy your own app!

1. Always try to **manually update** these libraries to their latest secure and stable versions.

2. Similarly, **patch old versions of the components with the newer ones**.

3. Before even adding these libraries in your project, **make a brief check on its security vulnerabilities** if they're listed and note down the possible solutions. 

## 7️⃣ Adding End-to-End Encryption 

When I first learned that WhatsApp chats will be end-to-end encrypted I was so much happy! Heck, they even have a [PDF](https://scontent.whatsapp.net/v/t61.22868-34/68135620_760356657751682_6212997528851833559_n.pdf/WhatsApp-Security-Whitepaper.pdf?_nc_sid=41cc27&_nc_ohc=BiDrtJ46xKYAX_7HHAI&_nc_ht=scontent.whatsapp.net&oh=248448dd22224f7b0f1772f32fec2ef9&oe=5F08D8D3) explaining how they do this... 

This encryption type makes sure that the data shared is involved within your React application and nowhere else. All third party will be denied access to transfer any confidential data. Read this article here on DEV which goes through the entire process of making a chat app on React with end-to-end encryption:

{% link https://dev.to/nickparsons/building-hipaa-compliant-end-to-end-encrypted-chat-with-stream-react-chat-and-virgil-security-2dfj %}

---

## Where to next? 🤔

Have a look at the following resources for more help:

- [3 Security Pitfalls Every React Developer Should Know](https://medium.com/swlh/3-security-pitfalls-every-react-developer-should-know-c04715b876b5)

- [React Security - course series by Ryan Chenkie](https://courses.reactsecurity.io/)

- [5 React Architecture Best Practices](https://www.sitepoint.com/react-architecture-best-practices/)

_Thanks for reading, I appreciate it! Have a good day. (✿◕‿◕✿)_

---

<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">This is why programming is great. Happy and satisfying from the beginning! Was your first programme &quot;Hello, World!&quot; as well?<br><br>Image source: <a href="https://t.co/RLdQCMX7gC">https://t.co/RLdQCMX7gC</a><a href="https://twitter.com/hashtag/DevHumour?src=hash&amp;ref_src=twsrc%5Etfw">#DevHumour</a> <a href="https://twitter.com/hashtag/Programming?src=hash&amp;ref_src=twsrc%5Etfw">#Programming</a> <a href="https://twitter.com/hashtag/Developer?src=hash&amp;ref_src=twsrc%5Etfw">#Developer</a> <a href="https://t.co/DAEr5pHNyM">pic.twitter.com/DAEr5pHNyM</a></p>&mdash; Microsoft Developer UK (@msdevUK) <a href="https://twitter.com/msdevUK/status/1278025510329749505?ref_src=twsrc%5Etfw">June 30, 2020</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

---

#### [📫 Subscribe to my weekly developer newsletter 📫](https://mailchi.mp/f59beeac6b9b/devupdates)

##### PS: From this year, I've decided to write here on DEV Community. Previously, I wrote on Medium. If anyone wants to take a look at my articles, [here](https://medium.com/@vaibhavkhulbe)'s my Medium profile.