eval() and new Function() execute a string as code. If any part of that string comes from a user, an attacker can run arbitrary code in your app. There is almost always a safer, specific tool for what eval was reaching for, and the fix is to use it instead of executing strings.
Why it's a problem
Whatever privileges your code has, injected code inherits. On a server that is often full access to your data and environment; in the browser it is your users' sessions. Even seemingly innocent uses, like eval to parse JSON or to look up a value by name, become remote code execution the moment the input is attacker-controlled.
The pattern
// runs whatever the user sends
const result = eval(req.query.expr);
const fn = new Function("return " + userInput)();The fix
// parse data with JSON, not eval
const data = JSON.parse(req.body.json);
// dispatch dynamically with a lookup map, not code execution
const handlers = { add, subtract };
const handler = handlers[req.query.op]; // undefined if not allowedWhy AI tools write this
eval is a compact way to express 'turn this string into behavior,' so when a prompt asks for a dynamic calculation or a configurable dispatch, it is a tempting completion. It runs in a demo with trusted input, and the injection only appears once real input flows in.
The quick fix
- Use JSON.parse for data instead of eval.
- Use a lookup map or switch for dynamic dispatch, not code execution.
- Never pass user input to eval() or new Function().