The eval Function
Explore how the eval function works and why it is considered risky in JavaScript security. Understand potential vulnerabilities like code injection and infinite loops. Learn how Content Security Policy (CSP) can help prevent attacks involving eval and improve application safety.
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 ...