Using `new Function` to validate JS syntax

I would like to verify (client-side) that the user has entered valid JavaScript code.

Pulling in a Javascript parser (e.g. Acorn or Esprima) is a relatively heavy dependency. However (if CSP is not enabled), I could do:

try {
    new Function(userCode);
    return {valid: true}
} catch (e) {
    return {
        valid: false,
        error: e.message

While this does use new Function, the user-provided code is never run, only parsed/compiled. Is there still a security issue?


  • This seems fine. Parsing/compiling JS code is safe and has no side effects (module resolution and loading does not apply in Function). We can be certain that JavaScript parsers used in modern browsers are pretty free of bugs.