Security best practices for React application
React-based web applications are growing every day due to the immense popularity of React. The react library has less vulnerability still it is not entirely secure.
Since React is compatible with other open-source components, things can be very quickly vulnerable if we those without authentic sources.
In this post, we are going to cover some Security best practices for React applications.
Validate the URLs:
The URLs can contain the dynamic script by using javascript: protocol in the URLs. We should use URL validation to protect it from script injection.
// Good const isValidUrl = (url) => { const parsed = new URL(url); return ['https:', 'http:'].indexOf(parsed.protocol) > -1; }; <a href={isValidUrl(url) ? url : ''}>Anchor link</a> // Bad <a href={url}>Anchor link</a>
Sanitize HTML before inserting into DOM:
We should sanitize any HTML before injecting it into DOM. We know dangerouslySetInnerHTML
is used to inject HTML into the DOM in React.
We can use the popular npm packages such as dompurify or others to Sanitize HTML before inserting into the DOM.
// Good import dompurify from "dompurify"; <div dangerouslySetInnerHTML={{ __html:dompurify.sanitize(HTMLdata) }} /> // Bad <div dangerouslySetInnerHTML={{ __html:HTMLdata }} />