javascript obfuscator

A javascript obfuscator rewrites a program so the file is harder to read. The program still has to run, so the rewrite has a limit. The package in the examples below is javascript-obfuscator 5.11.0. obfuscate() runs on your machine. It returns JavaScript.

const JavaScriptObfuscator = require("javascript-obfuscator");

const source = `function greet(name) {
  return "Hello, " + name;
}
`;

const result = JavaScriptObfuscator.obfuscate(source, {
  compact: false,
  controlFlowFlattening: false,
  deadCodeInjection: false,
  selfDefending: false,
  simplify: false,
  stringArray: false,
  seed: 1,
});

result.getObfuscatedCode();

obfuscate takes the source string and the options object. stringArray: false leaves the text "Hello, " in the function. seed: 1 fixes the generated names for this input, so a second call with the same source and the same options returns the same string. A seed of 0 is the unseeded generator. getObfuscatedCode() returns the rewritten program:

function greet(_0x231e35) {
    return 'Hello,\x20' + _0x231e35;
}

The parameter name is now _0x231e35. The space inside the greeting is the escape \x20. The function name greet is still there, because renameGlobals defaults to false. Call greet("Ada") and the return value is "Hello, Ada".

Standard obfuscation and a VM

That first output is still a function a debugger can step through. The usual extra step is the string array, which is on by default. String literals are lifted into an array, and the function reads them back through a helper. This call keeps the greeting, adds greet("Ada"), and turns the string array all the way on:

JavaScriptObfuscator.obfuscate(
  `function greet(name) {
  return "Hello, " + name;
}
greet("Ada");
`,
  {
    compact: false,
    controlFlowFlattening: false,
    deadCodeInjection: false,
    selfDefending: false,
    stringArray: true,
    stringArrayThreshold: 1,
    stringArrayEncoding: [],
    seed: 1,
    target: "node",
  }
);

The output is longer than the function below. This excerpt is the array and greet, not a program you can paste on its own:

function _0x18ac() {
    var _0x5e75ac = [
        '3319554DEAHfw',
        '2366646TNSHYi',
        '1043175bywcXH',
        '1623548TlSnvS',
        '3tJkExH',
        '34231UYCoTW',
        'Ada',
        '332158MWlhOU',
        '12515376KTsvhX',
        'Hello,\x20'
    ];
    _0x18ac = function () {
        return _0x5e75ac;
    };
    return _0x18ac();
}
function greet(_0x184466) {
    var _0x24ddd3 = _0x3fde;
    return _0x24ddd3(0x13d) + _0x184466;
}
greet(_0x7284fa(0x13a));

Above this array, the full output has a helper named _0x3fde and a loop. The loop shifts the array until a checksum matches 0x44bcb. The helper subtracts 0x135 from the number it is given, then reads that slot. 0x13d and 0x13a are arguments to that helper, not positions in the literal above, because the loop has already rotated the array. greet concatenates the helper’s result for 0x13d with its argument. The last line passes the helper’s result for 0x13a. Running the whole script produces "Hello, Ada".

stringArrayEncoding can then encode each stored string as base64 or rc4. The package inserts a decoder next to the array and runs it when the script loads. rc4 is the slower of the two. The README puts it at about 30 to 50 percent slower than base64. The decoder ships in the file, so anyone who runs the script runs the decoder.

controlFlowFlattening defaults to false. With compact set to false, the threshold set to 1, stringArray set to false, and seed set to 1, this function:

function price(qty) {
  return qty * 5 + " usd";
}

comes back with the * and the + stored as functions on an object, and with the string stored as a property:

function price(_0x1c58f4) {
    var _0x13ffba = {
        'XNYOZ': function (_0x24ab45, _0x16cfa2) {
            return _0x24ab45 + _0x16cfa2;
        },
        'iKwDD': function (_0x59512e, _0x5737ed) {
            return _0x59512e * _0x5737ed;
        },
        'umXST': '\x20usd'
    };
    return _0x13ffba['XNYOZ'](_0x13ffba['iKwDD'](_0x1c58f4, 0x5), _0x13ffba['umXST']);
}

price(2) is still "10 usd". The call XNYOZ is the +, and the call iKwDD is the *. The option warning says this can make runtime up to 1.5 times slower. controlFlowFlatteningThreshold (default 0.75) is the chance that a given node is flattened. deadCodeInjection defaults to false. Its warning says the file can grow by up to 200 percent, and turning it on forces stringArray on. deadCodeInjectionThreshold defaults to 0.4.

VM obfuscation is a different output. The package documents vmObfuscation as compiling function bodies into custom bytecode that an embedded interpreter runs, so an expression such as return qty * price is no longer sitting in the file as JavaScript. That option is not applied by obfuscate(). Passing vmObfuscation: true to obfuscate() still returns an ordinary function. The documented call is obfuscatePro(source, options, { apiToken }), which sends the source to the Obfuscator.io API. An invalid token rejects with ApiError and the message Invalid or expired API key. The Obfuscator.io FAQ says the API processes that source and discards it.

vmTargetFunctionsMode: "comment" limits the bytecode pass to functions marked with /* javascript-obfuscator:vm */. vmExcludeFunctions can leave a hot function, such as an animation loop, as ordinary JavaScript. Preset names for this path include vm-low-obfuscation, vm-default, vm-medium-obfuscation, vm-high-obfuscation, vm-ultra-high-obfuscation, and vm-anti-llm. obfuscate() cannot resolve those presets.

Self-defending code and debug protection

selfDefending defaults to false. Turn it on and the package forces compact to true, so the file is one line even if the options asked for compact: false. The README says the result is meant to break if a beautifier reformats it or renames its variables, and it says not to minify or edit that output afterward. A minifier belongs before this step, not after. If a minifier runs first, it has to keep comments such as /* javascript-obfuscator:vm */, or the later VM pass will not see them.

debugProtection defaults to false. The package warns that it can freeze the browser when Developer Tools are open, and it describes the option as blocking the debugger in WebKit-based browsers and in Firefox. debugProtectionInterval defaults to 0. When it is set to a millisecond delay, and debugProtection is also on, the package uses that interval to keep the Console tab in debug mode. The recommended range in the README is 2000 to 4000 milliseconds. The high-obfuscation preset sets the interval to 4000 and turns debugProtection on.

disableConsoleOutput defaults to false. In 5.11.0 the generated code replaces log, warn, info, error, exception, table, and trace on the global console. After that replacement, console.log("hi") prints nothing. The package warns that the change is global, so other scripts on the same page lose those methods too. The low-obfuscation, medium-obfuscation, and high-obfuscation presets all turn this option on. The default preset leaves it off.

domainLock defaults to an empty array, and domainLockRedirectUrl defaults to about:blank. The README says the script runs only on the listed hosts and otherwise redirects the browser. A leading dot, as in .example.com, is the documented way to include subdomains. www.example.com is that host only. target: "node" rejects domainLock. The validation error says the option is allowed only for browser and browser-no-eval.

Obfuscation and an LLM

The free transforms still emit JavaScript. A model that can read JavaScript can read the renamed function and the string-array helper. The package’s own comparison says those transforms include no LLM-specific defense.

The VM path is the one the package documents as harder for that kind of reading, because the protected function body is bytecode plus an interpreter rather than the original statements. vmDebugProtection is documented as adding anti-debugging, anti-analysis, and anti-LLM defenses to that runtime, and one of the Pro presets is named vm-anti-llm. The Obfuscator.io FAQ still says this only raises the effort, including for an AI assistant. It says reverse engineering is not impossible, because the program runs in an environment the attacker controls. Keep the decision that actually grants access on the server.

When to obfuscate

The reasons the project gives are client-side games, license checks, pricing, and other logic you do not want copied out of the file in one reading. Obfuscate code you wrote. The README says to leave vendor scripts and polyfills alone, and it puts the cost of obfuscating them at 15 to 80 percent slower, depending on the options, with a much larger file.

target defaults to "browser". "node" is the Node.js target. "browser-no-eval" is the browser target whose output does not use eval. For the small greet function above, the browser and node outputs were the same string. Browser-only options such as domainLock are still rejected when the target is node.

Obfuscation is not encryption

The Obfuscator.io FAQ says obfuscation is not encryption and is not a place to store an API key, a password, or any other secret. The string-array decoder, including the rc4 one, is in the file that runs in the browser. A person who can run the page can collect what the decoder returns. The FAQ’s alternatives are a server-side environment variable, a backend proxy in front of a third-party API, and a short-lived token that your server issues.

The same limit applies to source maps. sourceMap defaults to false. If you turn it on with sourceMapMode: "separate", getSourceMap() returns a JSON map whose sourcesContent field is the original source. Shipping that file gives the original back. The README’s own debugging tip is to keep the map at a URL you do not publish.

The FAQ also says the tool does not store your original names, so the output cannot be turned back into the file you started from. That is a reason to keep the original in version control. It is not a promise that nobody can reconstruct the behavior.

Running it, and what it costs

From the command line, the same package writes a file next to the input when you omit --output. The new name is the input name plus -obfuscated.

javascript-obfuscator greet.js --compact true --string-array false --self-defending false --seed 1

That command creates greet-obfuscated.js. For the greet function in the first example, the file is:

function greet(_0x231e35){return'Hello,\x20'+_0x231e35;}

--output out.js writes out.js instead. --options-preset accepts default, low-obfuscation, medium-obfuscation, or high-obfuscation. In 5.11.0, getOptionsByPreset("high-obfuscation") turns on control-flow flattening with threshold 1, dead-code injection with threshold 1, debug protection with a 4000 millisecond interval, self defending, rc4 string encoding, and stringArrayThreshold: 1. medium-obfuscation uses control-flow flattening at 0.75, dead-code injection at 0.4, and base64 string encoding, and it leaves debug protection off. Both of those presets turn on selfDefending and disableConsoleOutput.

The “1.5 times slower” figure and the “200 percent” figure are the warnings on those two options, not a measurement of one preset. The Obfuscator.io docs say to measure startup, the hot path, and the compressed size on the program you ship. Webpack, Rollup, esbuild, and Vite each have a plugin listed in the package README, and the same rule applies there: obfuscate your bundle, not the libraries inside it, and do that after the minifier.

If this article was helpful, tweet it!