The eval Function
Understand why eval is potentially JavaScript's most dangerous function and how we can use CSP to prevent its abuse.
We'll cover the following
The eval
or evil function?
The eval
function in JavaScript evaluates a script represented as a string and returns the result. Truthfully, it is rarely used in production, but it's such a powerful and potentially dangerous function that no course on JavaScript security is complete without discussing it. Mozilla Developer Network (MDN) goes as far as saying that we should never use eval
, and this is good advice unless we are 100% certain that eval
is something we require and our use case is safe.
The eval
function can be useful for running dynamically generated code, but this is a very specific use case and the code in question must be secure.
User input can't be trusted. Imagine the potential security vulnerabilities if we passed a user-provided string as a script to eval
. If a hacker were to construct a script with eval
and successfully inject it into another user's browser via XSS, they could run any JavaScript they'd like. What if eval
runs user-supplied code on the server? A simple infinite loop passed by a hacker could crash the system. The eval
function also executes the code it is given with the privileges of the caller, so an infinite loop is just one of many frightening scenarios.
Get hands-on with 1400+ tech skills courses.