How to Eliminate eval()
Using eval(), the Function() constructor,
or string-based setTimeout()/setInterval()
may require adding 'unsafe-eval' to your Content Security Policy,
which significantly weakens your security posture.
Security Risk
'unsafe-eval' allows attackers to execute arbitrary code if they can inject a string into your application.
This is a common vector for XSS attacks.
Why Remove eval()?
- Stronger CSP - Without
'unsafe-eval', your CSP blocks many XSS attack vectors - Better attestation - ScriptAttest can more accurately fingerprint scripts that don't use dynamic code generation
- Performance -
eval()prevents JavaScript engine optimizations
Common Patterns to Replace
1. JSON Parsing
Instead of using eval() to parse JSON:
const data = eval('(' + jsonString + ')'); const data = JSON.parse(jsonString); 2. Dynamic Property Access
Instead of using eval() for dynamic property access:
const value = eval('obj.' + propName); const value = obj[propName]; 3. setTimeout/setInterval with Strings
Passing strings to setTimeout requires unsafe-eval:
setTimeout('doSomething()', 1000); setTimeout(() => doSomething(), 1000);
// or
setTimeout(doSomething, 1000); 4. new Function()
The Function constructor is equivalent to eval():
const fn = new Function('a', 'b', 'return a + b'); const fn = (a, b) => a + b; Third-Party Libraries
Some third-party libraries use eval() internally. Common culprits include:
- • Google Tag Manager - Uses eval() to execute custom JavaScript variables. This is the most common source of eval() calls in modern websites.
- • Template engines - Lodash templates, Handlebars (use precompiled templates instead)
- • jQuery - Old versions of jQuery.globalEval()
- • Chart libraries - Some charting libraries compile expressions at runtime
- • JSON validators - Some schema validators use eval() for performance
ScriptAttest Detection
ScriptAttest's attestation scan detects all four types of security sinks in your scripts:
eval()- Direct code evaluationnew Function()- Function constructorsetTimeout(string)- String-based timeoutsetInterval(string)- String-based interval
Check your attestation report's "Security Sinks" section to see which scripts use these patterns.
Sinks are grouped by their originating domain (e.g., www.googletagmanager.com)
to help you identify the source.
When You Can't Remove eval()
If a third-party script absolutely requires 'unsafe-eval' and you can't replace it:
- Document the risk - Note which script requires it and why
- Isolate if possible - Consider loading the script in an iframe with a separate CSP
- Monitor closely - Use ScriptAttest to watch for behavioral changes in that script
- Request alternatives - Contact the vendor and ask for an unsafe-eval-free version
Need Help?
If you're struggling to eliminate eval() from your codebase, reach out to our support team. We can help analyze your attestation report and suggest alternatives.
Contact Support →