JavaScript Coding Violations
Cyclopt analyzes your JavaScript code to identify coding and security violations. Each check below lists its Rule ID, a description, and its source.
Use a check's Rule ID to silence a finding in code with a cyclopt-ignore comment, or to exclude it project-wide in the configuration file.
Enforces getter/setter pairs in objects and classes
Rule ID: accessor-pairs
Description: It's a common mistake in JavaScript to create an object with just a setter for a property but never have a corresponding getter defined for it. Without a getter, you cannot read the property, so it ends up not being used.
var o = {
set a(value) {
this.val = value;
}
};
var o = {
set a(value) {
this.val = value;
},
get a() {
return this.val;
}
};
Enforce line breaks after opening and before closing array brackets
Rule ID: array-bracket-newline
Description: A number of style guides require or disallow line breaks inside of array brackets.
Disallow or enforce spaces inside of brackets
Rule ID: array-bracket-spacing
Description: A number of style guides require or disallow spaces between array brackets and other tokens. This rule
Enforces return statements in callbacks of array's methods
Rule ID: array-callback-return
Description: Array has several methods for filtering, mapping, and folding.
var doubled = [1, 2, 3].map(function (x) {
x * 2;
});
var doubled = [1, 2, 3].map(function (x) {
return x * 2;
});
Enforce line breaks between array elements
Rule ID: array-element-newline
Description: A number of style guides require or disallow line breaks between array elements.
Require braces in arrow function body
Rule ID: arrow-body-style
Description: Arrow functions have two syntactic forms for their function bodies. They may be defined with a block body (denoted by curly braces) () => { ... } or with a single expression () => ..., whose value is implicitly returned.
const double = (x) => {
return x * 2;
};
const double = (x) => x * 2;
Require parens in arrow function arguments
Rule ID: arrow-parens
Description: Arrow functions can omit parentheses when they have exactly one parameter. In all other cases the parameter(s) must
const square = x => x * x;
const square = (x) => x * x;
Require space before/after arrow function's arrow
Rule ID: arrow-spacing
Description: This rule normalize style of spacing before/after an arrow function's arrow(=>).
Treat var as Block Scoped
Rule ID: block-scoped-var
Description: The block-scoped-var rule generates warnings when variables are used outside of the block in which they were defined. This emulates C-style block scope.
function f() {
if (true) {
var x = 1;
}
return x;
}
function f() {
var x;
if (true) {
x = 1;
}
return x;
}
Disallow or enforce spaces inside of blocks after opening block and before closing block
Rule ID: block-spacing
Description: This rule enforces consistent spacing inside an open block token and the next token on the same line. This rule also enforces consistent spacing inside a close block token and previous token on the same line.
Require or disallow the Unicode Byte Order Mark
Rule ID: BOM
Description: The Unicode Byte Order Mark (BOM) is used to specify whether code units are big
Require Brace Style
Rule ID: brace-style
Description: Brace style is closely related to indent style in programming and describes the placement of braces relative to their control statement and body. There are probably a dozen, if not more, brace styles in the world.
Enforce Return After Callback
Rule ID: callback-return
Description: The callback pattern is at the heart of most I/O and event-driven programming
Require CamelCase
Rule ID: camelcase
Description: When it comes to naming variables, style guides generally fall into one of two camps: camelcase (variableName) and underscores (variable_name). This rule focuses on using the camelcase approach. If your style guide calls for camelCasing your variable names, then this rule is for you!
var my_variable = 1;
var myVariable = 1;
Enforce or disallow capitalization of the first letter of a comment
Rule ID: capitalized-comments
Description: Comments are useful for leaving information for future developers. In order for that information to be useful and not distracting, it is sometimes desirable for comments to follow a particular style. One element of comment formatting styles is whether the first word of a comment should be capitalized or lowercase.
// this is a comment
var x = 1;
// This is a comment
var x = 1;
Enforce that class methods utilize this
Rule ID: class-methods-use-this
Description: If a class method does not use this, it can sometimes be made into a static function. If you do convert the method into a static function, instances of the class that call that particular method have to be converted to a static call as well (MyClass.callStaticMethod())
class A {
foo() {
return 1;
}
}
class A {
foo() {
return this.value;
}
}
Require or disallow trailing commas
Rule ID: comma-dangle
Description: Trailing commas in object literals are valid according to the ECMAScript 5 (and ECMAScript 3!) spec. However, IE8 (when not in IE8 document mode) and below will throw an error when it encounters trailing commas in JavaScript.
var arr = [
1,
2,
];
var arr = [
1,
2
];
Enforces spacing around commas
Rule ID: comma-spacing
Description: Spacing around commas improves readability of a list of items. Although most of the style guidelines for languages prescribe adding a space after a comma and not before it, it is subjective to the preferences of a project.
Comma style
Rule ID: comma-style
Description: The Comma Style rule enforces styles for comma-separated lists. There are two comma styles primarily used in JavaScript:
Limit Cyclomatic Complexity
Rule ID: complexity
Description: Cyclomatic complexity measures the number of linearly independent paths through a program's source code. This rule allows setting a cyclomatic complexity threshold.
Disallow or enforce spaces inside of computed properties
Rule ID: computed-property-spacing
Description: While formatting preferences are very personal, a number of style guides require
Require return statements to either always or never specify values
Rule ID: consistent-return
Description: Unlike statically-typed languages which enforce that a function returns a specified type of value, JavaScript allows different code paths in a function to return different types of values.
function f(a) {
if (a) {
return a;
}
return;
}
function f(a) {
if (a) {
return a;
}
return null;
}
Require Consistent This
Rule ID: consistent-this
Description: It is often necessary to capture the current execution context in order to make it available subsequently. A prominent example of this are jQuery callbacks:
Disallow use of the Buffer
Rule ID: constructor
Description: In Node.js, the behavior of the Buffer constructor is different depending on the type of its argument. Passing an argument from user input to Buffer() without validating its type can lead to security vulnerabilities such as remote memory disclosure and denial of service. As a result, the Buffer constructor has been deprecated and should not be used. Use the producer methods Buffer.from, Buffer.alloc, and Buffer.allocUnsafe instead.
Require Following Curly Brace Conventions
Rule ID: curly
Description: JavaScript allows the omission of curly braces when a block contains only one statement. However, it is considered by many to be best practice to never omit curly braces around blocks, even when they are optional, because it can lead to bugs and reduces code clarity. So the following:
if (x) doSomething();
if (x) {
doSomething();
}
Require Default Case in Switch Statements
Rule ID: default-case
Description: Some code conventions require that all switch statements have a default case, even if the default case is empty, such as:
switch (x) {
case 1:
doSomething();
break;
}
switch (x) {
case 1:
doSomething();
break;
default:
break;
}
Enforce default parameters to be last
Rule ID: default-param-last
Description: Putting default parameter at last allows function calls to omit optional tail arguments.
function f(a = 1, b) {
return a + b;
}
function f(b, a = 1) {
return a + b;
}
Enforce newline before and after dot
Rule ID: dot-location
Description: JavaScript allows you to place newlines before or after a dot in a member expression.
Require Dot Notation
Rule ID: dot-notation
Description: In JavaScript, one can access properties using the dot notation (foo.bar) or square-bracket notation (foo["bar"]). However, the dot notation is often preferred because it is easier to read, less verbose, and works better with aggressive JavaScript minimizers.
var x = foo["bar"];
var x = foo.bar;
Require or disallow newline at the end of files
Rule ID: eol-last
Description: Trailing newlines in non-empty files are a common UNIX idiom. Benefits of
Require === and !==
Rule ID: eqeqeq
Description: It is considered good practice to use the type-safe equality operators === and !== instead of their regular counterparts == and !=.
if (a == b) {
doSomething();
}
if (a === b) {
doSomething();
}
Enforce "for" loop update clause moving the counter in the right direction.
Rule ID: for-direction
Description: A for loop with a stop condition that can never be reached, such as one with a counter that moves in the wrong direction, will run infinitely. While there are occasions when an infinite loop is intended, the convention is to construct such loops as while loops.
for (let i = 0; i < 10; i--) {
doSomething(i);
}
for (let i = 0; i < 10; i++) {
doSomething(i);
}
Require or disallow spacing between function identifiers and their invocations
Rule ID: func-call-spacing
Description: When calling a function, developers may insert optional whitespace between the function's name and the parentheses that invoke it. The following pairs of function calls are equivalent:
Require function names to match the name of the variable or property to which they are assigned
Rule ID: func-name-matching
Description: This rule requires function names to match the name of the variable or property to which they are assigned.
var foo = function bar() {};
var foo = function foo() {};
Require or disallow named function expressions
Rule ID: func-names
Description: A pattern that's becoming more common is to give function expressions names to aid in debugging. For example:
var f = function () {
return 1;
};
var f = function f() {
return 1;
};
Enforce the consistent use of either function declarations or expressions
Rule ID: func-style
Description: There are two ways of defining functions in JavaScript: function declarations and function expressions. Declarations contain the function keyword first, followed by a name and then its arguments and the function body, for example:
function foo() {
return 1;
}
var foo = function () {
return 1;
};
Enforce line breaks between arguments of a function call
Rule ID: function-call-argument-newline
Description: A number of style guides require or disallow line breaks between arguments of a function call.
Enforce consistent line breaks inside function parentheses
Rule ID: function-paren-newline
Description: Many style guides require or disallow newlines inside of function parentheses.
Enforce spacing around the * in generator functions
Rule ID: generator-star-spacing
Description: Generators are a new type of function in ECMAScript 6 that can return multiple values over time.
Enforces that a return statement is present in property getters
Rule ID: getter-return
Description: The get syntax binds an object property to a function that will be called when that property is looked up. It was first introduced in ECMAScript 5:
var o = {
get name() {
this.foo = 1;
}
};
var o = {
get name() {
return this.foo;
}
};
Require grouped accessor pairs in object literals and classes
Rule ID: grouped-accessor-pairs
Description: A getter and setter for the same property don't necessarily have to be defined adjacent to each other.
const obj = {
get name() { return this._name; },
greet() {},
set name(value) { this._name = value; }
};
const obj = {
get name() { return this._name; },
set name(value) { this._name = value; },
greet() {}
};
Require Guarding for-in
Rule ID: guard-for-in
Description: Looping over objects with a for in loop will include properties that are inherited through the prototype chain. This behavior can lead to unexpected items in your for loop.
for (const key in obj) {
console.log(obj[key]);
}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(obj[key]);
}
}
Enforce Callback Error Handling
Rule ID: handle-callback-err
Description: In Node.js, a common pattern for dealing with asynchronous behavior is called the callback pattern.
function load(cb) {
fs.readFile('f', (err, data) => {
console.log(data);
});
}
function load(cb) {
fs.readFile('f', (err, data) => {
if (err) return cb(err);
console.log(data);
});
}
Disallow specified identifiers
Rule ID: id-blacklist
Description: > "There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
Enforce minimum and maximum identifier lengths
Rule ID: id-length
Description: Very short identifier names like e, x, _t or very long ones like hashGeneratorResultOutputContainerObject can make code harder to read and potentially less maintainable. To prevent this, one may enforce a minimum and/or maximum identifier length.
const x = 5;
const count = 5;
Require identifiers to match a specified regular expression
Rule ID: id-match
Description: > "There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
Enforce the location of arrow function bodies with implicit returns
Rule ID: implicit-arrow-linebreak
Description: An arrow function body can contain an implicit return as an expression instead of a block body. It can be useful to enforce a consistent location for the implicitly returned expression.
const foo = () =>
'value';
const foo = () => 'value';
Enforce consistent indentation
Rule ID: indent
Description: There are several common guidelines which require specific indentation of nested blocks and statements, like:
Enforce consistent indentation
Rule ID: indent-legacy
Description: ESLint 4.0.0 introduced a rewrite of the indent rule, which now reports more errors than it did in previous versions. To ease the process of migrating to 4.0.0, the indent-legacy rule was introduced as a snapshot of the indent rule from ESLint 3.x. If your build is failing after the upgrade to 4.0.0, you can disable indent and enable indent-legacy as a quick fix. Eventually, you should switch back to the indent rule to get bugfixes and improvements in future versions.
Require or disallow initialization in variable declarations
Rule ID: init-declarations
Description: In JavaScript, variables can be assigned during declaration, or at any point afterwards using an assignment statement. For example, in the following code, foo is initialized during declaration, while bar is initialized later.
let foo;
let foo = 1;
Enforce the consistent use of either double or single quotes in JSX attributes
Rule ID: jsx-quotes
Description: JSX attribute values can contain string literals, which are delimited with single or double quotes.
const el = <a href='/'>Home</a>;
const el = <a href="/">Home</a>;
Enforce consistent spacing between keys and values in object literal properties
Rule ID: key-spacing
Description: This rule enforces spacing around the colon in object literal properties. It can verify each property individually, or it can ensure horizontal alignment of adjacent properties in an object literal.
const obj = { foo : 42 };
const obj = { foo: 42 };
Enforce consistent spacing before and after keywords
Rule ID: keyword-spacing
Description: Keywords are syntax elements of JavaScript, such as try and if.
if (a) {
b();
}else {
c();
}
if (a) {
b();
} else {
c();
}
Enforce position of line comments
Rule ID: line-comment-position
Description: Line comments can be positioned above or beside code. This rule helps teams maintain a consistent style.
const x = 1; // this is a comment
// this is a comment
const x = 1;
Enforce consistent linebreak style
Rule ID: linebreak-style
Description: When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that
Require empty lines around comments
Rule ID: lines-around-comment
Description: Many style guides require empty lines before or after comments. The primary goal
Require or disallow newlines around directives
Rule ID: lines-around-directive
Description: This rule was deprecated in ESLint v4.0.0 and replaced by the padding-line-between-statements rule.
Require or disallow an empty line between class members
Rule ID: lines-between-class-members
Description: This rule improves readability by enforcing lines between class members. It will not check empty lines before the first member and after the last member, since that is already taken care of by padded-blocks.
class Foo {
bar() {}
baz() {}
}
class Foo {
bar() {}
baz() {}
}
Enforce a maximum number of classes per file
Rule ID: max-classes-per-file
Description: Files containing multiple classes can often result in a less navigable
Enforce a maximum depth that blocks can be nested
Rule ID: max-depth
Description: Many developers consider code difficult to read if blocks are nested beyond a certain depth.
function foo() {
if (a) {
if (b) {
if (c) {
if (d) {
bar();
}
}
}
}
}
function foo() {
if (a && b && c && d) {
bar();
}
}
Enforce a maximum line length
Rule ID: max-len
Description: Very long lines of code in any language can be difficult to read. In order to aid in readability and maintainability many coders have developed a convention to limit lines of code to X number of characters (traditionally 80 characters).
Enforce a maximum file length
Rule ID: max-lines
Description: Some people consider large files a code smell. Large files tend to do a lot of things and can make it hard following what's going. While there is not an objective maximum number of lines considered acceptable in a file, most people would agree it should not be in the thousands. Recommendations usually range from 100 to 500 lines.
Enforce a maximum function length
Rule ID: max-lines-per-function
Description: Some people consider large functions a code smell. Large functions tend to do a lot of things and can make it hard following what's going on. Many coding style guides dictate a limit of the number of lines that a function can comprise of. This rule can help enforce that style.
Enforce a maximum depth that callbacks can be nested
Rule ID: max-nested-callbacks
Description: Many JavaScript libraries use the callback pattern to manage asynchronous operations. A program of any complexity will most likely need to manage several asynchronous operations at various levels of concurrency. A common pitfall that is easy to fall into is nesting callbacks, which makes code more difficult to read the deeper the callbacks are nested.
a(() => {
b(() => {
c(() => {
d(() => {});
});
});
});
const handler = () => {};
a(() => b(() => c(handler)));
Enforce a maximum number of parameters in function definitions
Rule ID: max-params
Description: Functions that take numerous parameters can be difficult to read and write because it requires the memorization of what each parameter is, its type, and the order they should appear in. As a result, many coders adhere to a convention that caps the number of parameters a function can take.
function foo(a, b, c, d) {
return a + b + c + d;
}
function foo({ a, b, c, d }) {
return a + b + c + d;
}
Enforce a maximum number of statements allowed in function blocks
Rule ID: max-statements
Description: The max-statements rule allows you to specify the maximum number of statements allowed in a function.
Enforce a maximum number of statements allowed per line
Rule ID: max-statements-per-line
Description: A line of code containing too many statements can be difficult to read. Code is generally read from the top down, especially when scanning, so limiting the number of statements allowed on a single line can be very beneficial for readability and maintainability.
const a = 1; const b = 2;
const a = 1;
const b = 2;
Enforce a particular style for multiline comments
Rule ID: multiline-comment-style
Description: Many style guides require a particular style for comments that span multiple lines. For example, some style guides prefer the use of a single block comment for multiline comments, whereas other style guides prefer consecutive line comments.
Enforce or disallow newlines between operands of ternary expressions
Rule ID: multiline-ternary
Description: JavaScript allows operands of ternary expressions to be separated by newlines, which can improve the readability of your program.
const foo = bar ? value1 :
value2;
const foo = bar ? value1 : value2;
Require constructor names to begin with a capital letter
Rule ID: new-cap
Description: The new operator in JavaScript creates a new instance of a particular type of object. That type of object is represented by a constructor function. Since constructor functions are just regular functions, the only defining characteristic is that new is being used as part of the call. Native JavaScript functions begin with an uppercase letter to distinguish those functions that are to be used as constructors from functions that are not. Many style guides recommend following this pattern to more easily determine which functions are to be used as constructors.
const instance = new person();
const instance = new Person();
Require parentheses when invoking a constructor with no arguments
Rule ID: new-parens
Description: JavaScript allows the omission of parentheses when invoking a function via the new keyword and the constructor has no arguments. However, some coders believe that omitting the parentheses is inconsistent with the rest of the language and thus makes code less clear.
const foo = new Foo;
const foo = new Foo();
Require or disallow an empty line after variable declarations
Rule ID: newline-after-var
Description: This rule was deprecated in ESLint v4.0.0 and replaced by the padding-line-between-statements rule.
Require an empty line before return statements
Rule ID: newline-before-return
Description: This rule was deprecated in ESLint v4.0.0 and replaced by the padding-line-between-statements rule.
Require a newline after each call in a method chain
Rule ID: newline-per-chained-call
Description: Chained method calls on a single line without line breaks are harder to read, so some developers place a newline character after each method call in the chain to make it more readable and easy to maintain.
obj.method1().method2().method3().method4();
obj
.method1()
.method2()
.method3()
.method4();
Disallow Use of Alert
Rule ID: no-alert
Description: JavaScript's alert, confirm, and prompt functions are widely considered to be obtrusive as UI elements and should be replaced by a more appropriate custom UI implementation. Furthermore, alert is often used while debugging code, which should be removed before deployment to production.
alert('Hello');
console.log('Hello');
Disallow Array constructors
Rule ID: no-array-constructor
Description: Use of the Array constructor to construct a new array is generally
const arr = new Array(1, 2, 3);
const arr = [1, 2, 3];
Disallow using an async function as a Promise executor
Rule ID: no-async-promise-executor
Description: The new Promise constructor accepts an executor function as an argument, which has resolve and reject parameters that can be used to control the state of the created Promise. For example:
const p = new Promise(async (resolve, reject) => {
resolve(await fetch('/x'));
});
const p = new Promise((resolve, reject) => {
fetch('/x').then(resolve, reject);
});
Disallow await inside of loops
Rule ID: no-await-in-loop
Description: Performing an operation on each element of an iterable is a common task. However, performing an
async function foo(items) {
const results = [];
for (const item of items) {
results.push(await process(item));
}
return results;
}
async function foo(items) {
return Promise.all(items.map(item => process(item)));
}
Disallow bitwise operators
Rule ID: no-bitwise
Description: The use of bitwise operators in JavaScript is very rare and often & or | is simply a mistyped && or ||, which will lead to unexpected behavior.
const y = x & 1;
const y = x && 1;
Disallow Use of caller/callee
Rule ID: no-caller
Description: The use of arguments.caller and arguments.callee make several code optimizations impossible. They have been deprecated in future versions of JavaScript and their use is forbidden in ECMAScript 5 while in strict mode.
function foo() {
return arguments.callee;
}
function foo() {
return foo;
}
Disallow lexical declarations in case/default clauses
Rule ID: no-case-declarations
Description: This rule disallows lexical declarations (let, const, function and class)
switch (x) {
case 1:
const y = 2;
break;
}
switch (x) {
case 1: {
const y = 2;
break;
}
}
Disallow Shadowing of Variables Inside of catch
Rule ID: no-catch-shadow
Description: This rule was deprecated in ESLint v5.1.0.
Disallow modifying variables of class declarations
Rule ID: no-class-assign
Description: ClassDeclaration creates a variable, and we can modify the variable.
class A {}
A = 1;
class A {}
const B = A;
Disallow comparing against -0
Rule ID: no-compare-neg-zero
Description: The rule should warn against code that tries to compare against -0, since that will not work as intended. That is, code like x === -0 will pass for both +0 and -0.
if (x === -0) {
doSomething();
}
if (Object.is(x, -0)) {
doSomething();
}
Disallow assignment operators in conditional statements
Rule ID: no-cond-assign
Description: In conditional statements, it is very easy to mistype a comparison operator (such as ==) as an assignment operator (such as =). For example:
if (x = 5) {
doSomething();
}
if (x === 5) {
doSomething();
}
Disallow arrow functions where they could be confused with comparisons
Rule ID: no-confusing-arrow
Description: Arrow functions (=>) are similar in syntax to some comparison operators (>, <, <=, and >=). This rule warns against using the arrow function syntax in places where it could be confused with a comparison operator.
const x = a => 1 ? 2 : 3;
const x = a => (1 ? 2 : 3);
Disallow the use of console
Rule ID: no-console
Description: In JavaScript that is designed to be executed in the browser, it's considered a best practice to avoid using methods on console. Such messages are considered to be for debugging purposes and therefore not suitable to ship to the client. In general, calls using console should be stripped before being pushed to production.
console.log('hello');
logger.info('hello');
Disallow modifying variables that are declared using const
Rule ID: no-const-assign
Description: We cannot modify variables that are declared using const keyword.
const a = 0;
a = 1;
let a = 0;
a = 1;
Disallow constant expressions in conditions
Rule ID: no-constant-condition
Description: A constant expression (for example, a literal) as a test condition might be a typo or development trigger for a specific behavior. For example, the following code looks as if it is not ready for production.
if (true) {
doSomething();
}
if (x) {
doSomething();
}
Disallow returning value in constructor
Rule ID: no-constructor-return
Description: In JavaScript, returning a value in the constructor of a class may be a mistake. Forbidding this pattern prevents mistakes resulting from unfamiliarity with the language or a copy-paste error.
class A {
constructor() {
return { a: 1 };
}
}
class A {
constructor() {
this.a = 1;
}
}
Disallow continue statements
Rule ID: no-continue
Description: The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. When used incorrectly it makes code less testable, less readable and less maintainable. Structured control flow statements such as if should be used instead.
for (const x of list) {
if (x.skip) continue;
process(x);
}
for (const x of list) {
if (!x.skip) {
process(x);
}
}
Disallow control characters in regular expressions
Rule ID: no-control-regex
Description: Control characters are special, invisible characters in the ASCII range 0-31. These characters are rarely used in JavaScript strings so a regular expression containing these characters is most likely a mistake.
const pattern = /\x1f/;
const pattern = /\x20/;
Disallow the use of debugger
Rule ID: no-debugger
Description: The debugger statement is used to tell the executing JavaScript environment to stop execution and start up a debugger at the current point in the code. This has fallen out of favor as a good practice with the advent of modern debugging and development tools. Production code should definitely not contain debugger, as it will cause the browser to stop executing code and open an appropriate debugger.
function foo() {
debugger;
return 1;
}
function foo() {
return 1;
}
Disallow deleting variables
Rule ID: no-delete-var
Description: The purpose of the delete operator is to remove a property from an object. Using the delete operator on a variable might lead to unexpected behavior.
var x = 1;
delete x;
var x = 1;
x = undefined;
Disallow Regular Expressions That Look Like Division
Rule ID: no-div-regex
Description: Require regex literals to escape division operators.
const re = /=foo/;
const re = /[=]foo/;
Disallow duplicate arguments in function definitions
Rule ID: no-dupe-args
Description: If more than one parameter has the same name in a function definition, the last occurrence "shadows" the preceding occurrences. A duplicated name might be a typing error.
function foo(a, b, a) {
return a + b;
}
function foo(a, b, c) {
return a + b + c;
}
Disallow duplicate name in class members
Rule ID: no-dupe-class-members
Description: If there are declarations of the same name in class members, the last declaration overwrites other declarations silently.
class A {
foo() {}
foo() {}
}
class A {
foo() {}
bar() {}
}
Disallow duplicate conditions in if-else-if chains
Rule ID: no-dupe-else-if
Description: if-else-if chains are commonly used when there is a need to execute only one branch (or at most one branch) out of several possible branches, based on certain conditions.
if (a) {
f();
} else if (a) {
g();
}
if (a) {
f();
} else if (b) {
g();
}
Disallow duplicate keys in object literals
Rule ID: no-dupe-keys
Description: Multiple properties with the same key in object literals can cause unexpected behavior in your application.
const obj = {
a: 1,
a: 2,
};
const obj = {
a: 1,
b: 2,
};
Rule to disallow a duplicate case label
Rule ID: no-duplicate-case
Description: If a switch statement has duplicate test expressions in case clauses, it is likely that a programmer copied a case clause but forgot to change the test expression.
switch (x) {
case 1:
break;
case 1:
break;
}
switch (x) {
case 1:
break;
case 2:
break;
}
Disallow duplicate imports
Rule ID: no-duplicate-imports
Description: Using a single import statement per module will make the code clearer because you can see everything being imported from that module on one line.
import { a } from 'mod';
import { b } from 'mod';
import { a, b } from 'mod';
Disallow return before else
Rule ID: no-else-return
Description: If an if block contains a return statement, the else block becomes unnecessary. Its contents can be placed outside of the block.
function foo() {
if (x) {
return 1;
} else {
return 2;
}
}
function foo() {
if (x) {
return 1;
}
return 2;
}
Disallow empty block statements
Rule ID: no-empty
Description: Empty block statements, while not technically errors, usually occur due to refactoring that wasn't completed. They can cause confusion when reading code.
if (x) {
}
if (x) {
doSomething();
}
Disallow empty character classes in regular expressions
Rule ID: no-empty-character-class
Description: Because empty character classes in regular expressions do not match anything, they might be typing mistakes.
const re = /abc[]def/;
const re = /abc[a-z]def/;
Disallow empty functions
Rule ID: no-empty-function
Description: Empty functions can reduce readability because readers need to guess whether it's intentional or not.
function foo() {}
function foo() {
// intentionally empty
}
Disallow empty destructuring patterns
Rule ID: no-empty-pattern
Description: When using destructuring, it's possible to create a pattern that has no effect. This happens when empty curly braces are used to the right of an embedded object destructuring pattern, such as:
const {} = foo;
const { a } = foo;
Disallow Null Comparisons
Rule ID: no-eq-null
Description: Comparing to null without a type-checking operator (== or !=), can have unintended results as the comparison will evaluate to true when comparing to not just a null, but also an undefined value.
if (x == null) {
doSomething();
}
if (x === null) {
doSomething();
}
Disallow reassigning exceptions in catch clauses
Rule ID: no-ex-assign
Description: If a catch clause in a try statement accidentally (or purposely) assigns another value to the exception parameter, it impossible to refer to the error from that point on.
try {
doSomething();
} catch (e) {
e = 10;
}
try {
doSomething();
} catch (e) {
const code = 10;
}
Disallow Extending of Native Objects
Rule ID: no-extend-native
Description: In JavaScript, you can extend any object, including builtin or "native" objects. Sometimes people change the behavior of these native objects in ways that break the assumptions made about them in other parts of the code.
Object.prototype.foo = function () {};
function foo(obj) {}
Disallow unnecessary function binding
Rule ID: no-extra-bind
Description: The bind() method is used to create functions with specific this values and, optionally, binds arguments to specific values. When used to specify the value of this, it's important that the function actually uses this in its function body. For example:
const f = function () {
return 1;
}.bind(this);
const f = function () {
return 1;
};
Disallow unnecessary boolean casts
Rule ID: no-extra-boolean-cast
Description: In contexts such as an if statement's test where the result of the expression will already be coerced to a Boolean, casting to a Boolean via double negation (!!) or a Boolean call is unnecessary. For example, these if statements are equivalent:
if (!!x) {
doSomething();
}
if (x) {
doSomething();
}
Disallow Unnecessary Labels
Rule ID: no-extra-label
Description: If a loop contains no nested loops or switches, labeling the loop is unnecessary.
loop: while (true) {
break loop;
}
while (true) {
break;
}
Disallow unnecessary parentheses
Rule ID: no-extra-parens
Description: This rule restricts the use of parentheses to only where they are necessary.
Disallow unnecessary semicolons
Rule ID: no-extra-semi
Description: Typing mistakes and misunderstandings about where semicolons are required can lead to semicolons that are unnecessary. While not technically an error, extra semicolons can cause confusion when reading code.
const x = 5;;
const x = 5;
Disallow Case Statement Fallthrough
Rule ID: no-fallthrough
Description: The switch statement in JavaScript is one of the more error-prone constructs of the language thanks in part to the ability to "fall through" from one case to the next. For example:
switch (x) {
case 1:
doA();
case 2:
doB();
}
switch (x) {
case 1:
doA();
break;
case 2:
doB();
}
Disallow Floating Decimals
Rule ID: no-floating-decimal
Description: Float values in JavaScript contain a decimal point, and there is no requirement that the decimal point be preceded or followed by a number. For example, the following are all valid JavaScript numbers:
var num = .5;
var amount = 2.;
var total = -.7;
var num = 0.5;
var amount = 2.0;
var total = -0.7;
Disallow reassigning function declarations
Rule ID: no-func-assign
Description: JavaScript functions can be written as a FunctionDeclaration function foo() { ... } or as a FunctionExpression var foo = function() { ... };. While a JavaScript interpreter might tolerate it, overwriting/reassigning a function written as a FunctionDeclaration is often indicative of a mistake or issue.
function foo() {}
foo = bar;
var foo = function () {};
foo = bar;
Disallow assignment to native objects or read-only global variables
Rule ID: no-global-assign
Description: JavaScript environments contain a number of built-in global variables, such as window in browsers and process in Node.js. In almost all cases, you don't want to assign a value to these global variables as doing so could result in losing access to important functionality. For example, you probably don't want to do this in browser code:
window = {};
Object = null;
var myWindow = {};
var myObject = null;
Disallow the type conversion with shorter notations.
Rule ID: no-implicit-coercion
Description: In JavaScript, there are a lot of different ways to convert value types.
var b = !!foo;
var n = +foo;
var s = "" + foo;
var b = Boolean(foo);
var n = Number(foo);
var s = String(foo);
Disallow declarations in the global scope
Rule ID: no-implicit-globals
Description: It is the best practice to avoid 'polluting' the global scope with variables that are intended to be local to the script.
foo = 1;
var bar = 2;
window.foo = 1;
window.bar = 2;
Disallow assigning to imported bindings
Rule ID: no-import-assign
Description: The updates of imported bindings by ES Modules cause runtime errors.
import mod from "./mod.js";
mod = 1;
import mod from "./mod.js";
var copy = mod;
copy = 1;
Disallow inline comments after code
Rule ID: no-inline-comments
Description: Some style guides disallow comments on the same line as code. Code can become difficult to read if comments immediately follow the code on the same line.
var a = 1; // set a to one
// set a to one
var a = 1;
Disallow variable or function declarations in nested blocks
Rule ID: no-inner-declarations
Description: In JavaScript, prior to ES6, a function declaration is only allowed in the first level of a program or the body of another function, though parsers sometimes erroneously accept them elsewhere. This only applies to function declarations; named or anonymous function expressions can occur anywhere an expression is permitted.
if (test) {
function doSomething() {}
}
function doSomething() {}
if (test) {
doSomething();
}
Disallow invalid regular expression strings in RegExp constructors
Rule ID: no-invalid-regexp
Description: An invalid pattern in a regular expression literal is a SyntaxError when the code is parsed, but an invalid string in RegExp constructors throws a SyntaxError only when the code is executed.
var re = new RegExp("[");
var re = new RegExp("\\[");
Disallow this keywords outside of classes or class-like objects.
Rule ID: no-invalid-this
Description: Under the strict mode, this keywords outside of classes or class-like objects might be undefined and raise a TypeError.
Disallow irregular whitespace
Rule ID: no-irregular-whitespace
Description: Invalid or irregular whitespace causes issues with ECMAScript 5 parsers and also makes code harder to debug in a similar nature to mixed tabs and spaces.
var thing = function () /*<NBSP>*/ {
return 1;
};
var thing = function () {
return 1;
};
Disallow Iterator
Rule ID: no-iterator
Description: The __iterator__ property was a SpiderMonkey extension to JavaScript that could be used to create custom iterators that are compatible with JavaScript's for in and for each constructs. However, this property is now obsolete, so it should not be used. Here's an example of how this used to work:
foo.__iterator__ = function () {};
foo[Symbol.iterator] = function () {};
Disallow Labels That Are Variables Names
Rule ID: no-label-var
Description: This rule aims to create clearer code by disallowing the bad practice of creating a label that shares a name with a variable that is in scope.
var x = 1;
x:
while (true) {
break x;
}
var x = 1;
loop:
while (true) {
break loop;
}
Disallow Labeled Statements
Rule ID: no-labels
Description: Labeled statements in JavaScript are used in conjunction with break and continue to control flow around multiple loops. For example:
outer:
for (var i = 0; i < 10; i++) {
break outer;
}
for (var i = 0; i < 10; i++) {
break;
}
Disallow Unnecessary Nested Blocks
Rule ID: no-lone-blocks
Description: In JavaScript, prior to ES6, standalone code blocks delimited by curly braces do not create a new scope and have no use. For example, these curly braces do nothing to foo:
{
var foo = 1;
}
var foo = 1;
Disallow if statements as the only statement in else blocks
Rule ID: no-lonely-if
Description: If an if statement is the only statement in the else block, it is often clearer to use an else if form.
if (a) {
foo();
} else {
if (b) {
bar();
}
}
if (a) {
foo();
} else if (b) {
bar();
}
Disallow Functions in Loops
Rule ID: no-loop-func
Description: Writing functions within loops tends to result in errors due to the way the function creates a closure around the loop. For example:
for (var i = 0; i < 10; i++) {
funcs.push(function () { return i; });
}
for (let i = 0; i < 10; i++) {
funcs.push(function () { return i; });
}
Disallow Magic Numbers
Rule ID: no-magic-numbers
Description: 'Magic numbers' are numbers that occur multiple times in code without an explicit meaning.
var total = price * 1.15;
var TAX_RATE = 1.15;
var total = price * TAX_RATE;
Disallow characters which are made with multiple code points in character class syntax
Rule ID: no-misleading-character-class
Description: Unicode includes the characters which are made with multiple code points.
Disallow mixes of different operators
Rule ID: no-mixed-operators
Description: Enclosing complex expressions by parentheses clarifies the developer's intention, which makes the code more readable.
var foo = a && b || c;
var foo = (a && b) || c;
Disallow require calls to be mixed with regular variable declarations
Rule ID: no-mixed-requires
Description: In the Node.js community it is often customary to separate initializations with calls to require modules from other variable declarations, sometimes also grouping them by the type of module. This rule helps you enforce this convention.
Disallow mixed spaces and tabs for indentation
Rule ID: no-mixed-spaces-and-tabs
Description: Most code conventions require either tabs or spaces be used for indentation. As such, it's usually an error if a single line of code is indented with both tabs and spaces.
Disallow Use of Chained Assignment Expressions
Rule ID: no-multi-assign
Description: Chaining the assignment of variables can lead to unexpected results and be difficult to read.
var a = b = c = 5;
var a = 5;
var b = 5;
var c = 5;
Disallow multiple spaces
Rule ID: no-multi-spaces
Description: Multiple spaces in a row that are not used for indentation are typically mistakes. For example:
var a = 1;
var a = 1;
Disallow Multiline Strings
Rule ID: no-multi-str
Description: It's possible to create multiline strings in JavaScript by using a slash before a newline, such as:
var x = "Line one \
Line two";
var x = "Line one " +
"Line two";
Disallow multiple empty lines
Rule ID: no-multiple-empty-lines
Description: Some developers prefer to have multiple blank lines removed, while others feel that it helps improve readability. Whitespace is useful for separating logical sections of code, but excess whitespace takes up more of the screen.
Disallow Reassignment of Native Objects
Rule ID: no-native-reassign
Description: This rule was deprecated in ESLint v3.3.0 and replaced by the no-global-assign rule.
Disallow negated conditions
Rule ID: no-negated-condition
Description: Negated conditions are more difficult to understand. Code can be made more readable by inverting the condition instead.
if (!a) {
doB();
} else {
doA();
}
if (a) {
doA();
} else {
doB();
}
Disallow negating the left operand in in expressions
Rule ID: no-negated-in-lhs
Description: This rule was deprecated in ESLint v3.3.0 and replaced by the no-unsafe-negation rule.
Disallow nested ternary expressions
Rule ID: no-nested-ternary
Description: Nesting ternary expressions can make code more difficult to understand.
var result = a ? b : c ? d : e;
var result;
if (a) {
result = b;
} else {
result = c ? d : e;
}
Disallow new For Side Effects
Rule ID: no-new
Description: The goal of using new with a constructor is typically to create an object of a particular type and store that object in a variable, such as:
new Thing();
var thing = new Thing();
Disallow Function Constructor
Rule ID: no-new-func
Description: It's possible to create functions in JavaScript using the Function constructor, such as:
var add = new Function("a", "b", "return a + b");
var add = function (a, b) { return a + b; };
Disallow Object constructors
Rule ID: no-new-object
Description: The Object constructor is used to create new generic objects in JavaScript, such as:
var obj = new Object();
var obj = {};
Disallow new require
Rule ID: no-new-require
Description: The require function is used to include modules that exist in separate files, such as:
var appHeader = new require("app-header");
var AppHeader = require("app-header");
var appHeader = new AppHeader();
Disallow Symbol Constructor
Rule ID: no-new-symbol
Description: Symbol is not intended to be used with the new operator, but to be called as a function.
var sym = new Symbol("foo");
var sym = Symbol("foo");
Disallow Primitive Wrapper Instances
Rule ID: no-new-wrappers
Description: There are three primitive types in JavaScript that have wrapper objects: string, number, and boolean. These are represented by the constructors String, Number, and Boolean, respectively. The primitive wrapper types are used whenever one of these primitive values is read, providing them with object-like capabilities such as methods. Behind the scenes, an object of the associated wrapper type is created and then destroyed, which is why you can call methods on primitive values, such as:
var str = new String("Hello");
var str = String("Hello");
Disallow calling global object properties as functions
Rule ID: no-obj-calls
Description: ECMAScript provides several global objects that are intended to be used as-is. Some of these objects look as if they could be constructors due their capitalization (such as Math and JSON) but will throw an error if you try to execute them as functions.
var math = Math();
var math = Math.floor(1.5);
Disallow octal literals
Rule ID: no-octal
Description: Octal literals are numerals that begin with a leading zero, such as:
var num = 071;
var num = 57;
Disallow octal escape sequences in string literals
Rule ID: no-octal-escape
Description: As of the ECMAScript 5 specification, octal escape sequences in string literals are deprecated and should not be used. Unicode escape sequences should be used instead.
var foo = "Copyright \251";
var foo = "Copyright \u00A9";
Disallow Reassignment of Function Parameters
Rule ID: no-param-reassign
Description: Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object. Often, assignment to function parameters is unintended and indicative of a mistake or programmer error.
function foo(bar) {
bar = 13;
}
function foo(bar) {
var baz = 13;
}
Disallow string concatenation when using __dirname and __filename
Rule ID: no-path-concat
Description: In Node.js, the __dirname and __filename global variables contain the directory path and the file path of the currently executing script file, respectively. Sometimes, developers try to use these variables to create paths to other files, such as:
const fullPath = __dirname + "/foo.js";
const path = require("path");
const fullPath = path.join(__dirname, "foo.js");
Disallow the unary operators ++ and --
Rule ID: no-plusplus
Description: Because the unary ++ and -- operators are subject to automatic semicolon insertion, differences in whitespace can change semantics of source code.
let i = 0;
i++;
let i = 0;
i += 1;
Disallow process.env
Rule ID: no-process-env
Description: The process.env object in Node.js is used to store deployment/configuration parameters. Littering it through out a project could lead to maintenance issues as it's another kind of global dependency. As such, it could lead to merge conflicts in a multi-user setup and deployment issues in a multi-server setup. Instead, one of the best practices is to define all those parameters in a single configuration/settings file which could be accessed throughout the project.
const port = process.env.PORT;
const config = require("./config");
const port = config.port;
Disallow Use of __proto__
Rule ID: no-proto
Description: __proto__ property has been deprecated as of ECMAScript 3.1 and shouldn't be used in the code. Use Object.getPrototypeOf and Object.setPrototypeOf instead.
const proto = obj.__proto__;
const proto = Object.getPrototypeOf(obj);
Disallow use of Object.prototypes builtins directly
Rule ID: no-prototype-builtins
Description: In ECMAScript 5.1, Object.create was added, which enables the creation of objects with a specified [[Prototype]]. Object.create(null) is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype. This rule prevents calling some Object.prototype methods directly from an object.
if (obj.hasOwnProperty("foo")) {}
if (Object.prototype.hasOwnProperty.call(obj, "foo")) {}
Disallow Variable Redeclaration
Rule ID: no-redeclare
Description: In JavaScript, it's possible to redeclare the same variable name using var. This can lead to confusion as to where the variable is actually declared and initialized.
var a = 1;
var a = 2;
var a = 1;
a = 2;
Disallow multiple spaces in regular expression literals
Rule ID: no-regex-spaces
Description: Regular expressions can be very complex and difficult to understand, which is why it's important to keep them as simple as possible in order to avoid mistakes. One of the more error-prone things you can do with a regular expression is to use more than one space, such as:
const re = /foo bar/;
const re = /foo {3}bar/;
Disallow specific global variables
Rule ID: no-restricted-globals
Description: Disallowing usage of specific global variables can be useful if you want to allow a set of global
Disallow specific imports
Rule ID: no-restricted-imports
Description: Imports are an ES6/ES2015 standard for making the functionality of other modules available in your current module. In CommonJS this is implemented through the require() call which makes this ESLint rule roughly equivalent to its CommonJS counterpart no-restricted-modules.
Disallow Node.js modules
Rule ID: no-restricted-modules
Description: A module in Node.js is a simple or complex functionality organized in a JavaScript file which can be reused throughout the Node.js
Disallow certain object properties
Rule ID: no-restricted-properties
Description: Certain properties on objects may be disallowed in a codebase. This is useful for deprecating an API or restricting usage of a module's methods. For example, you may want to disallow using describe.only when using Mocha or telling people to use Object.assign instead of _.extend.
Disallow specified syntax
Rule ID: no-restricted-syntax
Description: JavaScript has a lot of language features, and not everyone likes all of them. As a result, some projects choose to disallow the use of certain language features altogether. For instance, you might decide to disallow the use of try-catch or class, or you might decide to disallow the use of the in operator.
Disallow Assignment in return Statement
Rule ID: no-return-assign
Description: One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a return statement. For example:
function foo(a) {
return a = 5;
}
function foo(a) {
return a === 5;
}
Disallows unnecessary return await
Rule ID: no-return-await
Description: Inside an async function, return await is seldom useful. Since the return value of an async function is always wrapped in Promise.resolve, return await doesn’t actually do anything except add extra time before the overarching Promise resolves or rejects. The only valid exception is if return await is used in a try/catch statement to catch errors from another Promise-based function.
async function foo() {
return await bar();
}
async function foo() {
return bar();
}
Disallow Script URLs
Rule ID: no-script-url
Description: Using javascript: URLs is considered by some as a form of eval. Code passed in javascript: URLs has to be parsed and evaluated by the browser in the same way that eval is processed.
const url = "javascript:void(0)";
const url = "#";
Disallow Self Assignment
Rule ID: no-self-assign
Description: Self assignments have no effect, so probably those are an error due to incomplete refactoring.
let foo = 1;
foo = foo;
let foo = 1;
foo = bar;
Disallow Self Compare
Rule ID: no-self-compare
Description: Comparing a variable against itself is usually an error, either a typo or refactoring error. It is confusing to the reader and may potentially introduce a runtime error.
if (x === x) {}
if (x === y) {}
Disallow Use of the Comma Operator
Rule ID: no-sequences
Description: The comma operator includes multiple expressions where only one is expected. It evaluates each operand from left to right and returns the value of the last operand. However, this frequently obscures side effects, and its use is often an accident. Here are some examples of sequences:
const x = (doStuff(), 5);
doStuff();
const x = 5;
Disallow returning values from setters
Rule ID: no-setter-return
Description: Setters cannot return values.
const obj = {
set foo(val) {
return val;
}
};
const obj = {
set foo(val) {
this._foo = val;
}
};
Disallow variable declarations from shadowing variables declared in the outer scope
Rule ID: no-shadow
Description: Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. For example:
const a = 3;
function foo() {
const a = 10;
}
const a = 3;
function foo() {
const b = 10;
}
Disallow Shadowing of Restricted Names
Rule ID: no-shadow-restricted-names
Description: ES5 §15.1.1 Value Properties of the Global Object (NaN, Infinity, undefined) as well as strict mode restricted identifiers eval and arguments are considered to be restricted names in JavaScript. Defining them to mean something else can have unintended consequences and confuse others reading the code. For example, there's nothing preventing you from writing:
function foo(undefined) {}
function foo(value) {}
Disallow spacing between function identifiers and their applications
Rule ID: no-spaced-func
Description: This rule was deprecated in ESLint v3.3.0 and replaced by the func-call-spacing rule.
Disallow sparse arrays
Rule ID: no-sparse-arrays
Description: Sparse arrays contain empty slots, most frequently due to multiple commas being used in an array literal, such as:
const items = [1, , 3];
const items = [1, 2, 3];
Disallow Synchronous Methods
Rule ID: no-sync
Description: In Node.js, most I/O is done through asynchronous methods. However, there are often synchronous versions of the asynchronous methods. For example, fs.exists() and fs.existsSync(). In some contexts, using synchronous operations is okay (if, as with ESLint, you are writing a command line utility). However, in other contexts the use of synchronous operations is considered a bad practice that should be avoided. For example, if you are running a high-travel web server on Node.js, you should consider carefully if you want to allow any synchronous operations that could lock up the server.
const data = fs.readFileSync("file.txt");
const data = await fs.promises.readFile("file.txt");
Disallow all tabs
Rule ID: no-tabs
Description: Some style guides don't allow the use of tab characters at all, including within comments.
Disallow template literal placeholder syntax in regular strings
Rule ID: no-template-curly-in-string
Description: ECMAScript 6 allows programmers to create strings containing variable or expressions using template literals, instead of string concatenation, by writing expressions like '${variable}' between two backtick quotes ('). It can be easy to use the wrong quotes when wanting to use template literals, by writing '"${variable}"', and end up with the literal value '"${variable}"' instead of a string containing the value of the injected expressions.
const msg = "Hello ${name}";
const msg = `Hello ${name}`;
Disallow ternary operators
Rule ID: no-ternary
Description: The ternary operator is used to conditionally assign a value to a variable. Some believe that the use of ternary operators leads to unclear code.
const x = cond ? 1 : 2;
let x;
if (cond) {
x = 1;
} else {
x = 2;
}
Restrict what can be thrown as an exception
Rule ID: no-throw-literal
Description: It is considered good practice to only throw the Error object itself or an object using the Error object as base objects for user-defined exceptions.
throw "error occurred";
throw new Error("error occurred");
Disallow trailing whitespace at the end of lines
Rule ID: no-trailing-spaces
Description: Sometimes in the course of editing files, you can end up with extra whitespace at the end of lines. These whitespace differences can be picked up by source control systems and flagged as diffs, causing frustration for developers. While this extra whitespace causes no functional issues, many code conventions require that trailing spaces be removed before check-in.
Disallow Undeclared Variables
Rule ID: no-undef
Description: This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var keyword in a for loop initializer).
foo = 10;
var foo;
foo = 10;
Disallow Initializing to undefined
Rule ID: no-undef-init
Description: In JavaScript, a variable that is declared and not initialized to any value automatically gets the value of undefined. For example:
let foo = undefined;
let foo;
Disallow Use of undefined Variable
Rule ID: no-undefined
Description: The undefined variable in JavaScript is actually a property of the global object. As such, in ECMAScript 3 it was possible to overwrite the value of undefined. While ECMAScript 5 disallows overwriting undefined, it's still possible to shadow undefined, such as:
const x = undefined;
let x;
Disallow dangling underscores in identifiers
Rule ID: no-underscore-dangle
Description: As far as naming conventions for identifiers go, dangling underscores may be the most polarizing in JavaScript. Dangling underscores are underscores at either the beginning or end of an identifier, such as:
const _foo = 1;
const foo = 1;
Disallow confusing multiline expressions
Rule ID: no-unexpected-multiline
Description: Semicolons are usually optional in JavaScript, because of automatic semicolon insertion (ASI). You can require or disallow semicolons with the semi rule.
Disallow unmodified conditions of loops
Rule ID: no-unmodified-loop-condition
Description: Variables in a loop condition often are modified in the loop.
Disallow ternary operators when simpler alternatives exist
Rule ID: no-unneeded-ternary
Description: It's a common mistake in JavaScript to use a conditional expression to select between two Boolean values instead of using ! to convert the test to a Boolean.
const isYes = cond ? true : false;
const isYes = Boolean(cond);
Disallow unreachable code after return, throw, continue, and break statements
Rule ID: no-unreachable
Description: Because the return, throw, break, and continue statements unconditionally exit a block of code, any statements after them cannot be executed. Unreachable statements are usually a mistake.
function foo() {
return true;
console.log("never runs");
}
function foo() {
console.log("runs");
return true;
}
Disallow control flow statements in finally blocks
Rule ID: no-unsafe-finally
Description: JavaScript suspends the control flow statements of try and catch blocks until the execution of finally block finishes. So, when return, throw, break, or continue is used in finally, control flow statements inside try and catch are overwritten, which is considered as unexpected behavior. Such as:
function foo() {
try {
return 1;
} finally {
return 2;
}
}
function foo() {
let result;
try {
result = 1;
} finally {
console.log("cleanup");
}
return result;
}
Disallow negating the left operand of relational operators
Rule ID: no-unsafe-negation
Description: Just as developers might type -a + b when they mean -(a + b) for the negative of a sum, they might type !key in object by mistake when they almost certainly mean !(key in object) to test that a key is not in an object. !obj instanceof Ctor is similar.
if (!key in object) {
doSomething();
}
if (!(key in object)) {
doSomething();
}
Disallow Unused Expressions
Rule ID: no-unused-expressions
Description: An unused expression which has no effect on the state of the program indicates a logic error.
a && b();
if (a) {
b();
}
Disallow Unused Labels
Rule ID: no-unused-labels
Description: Labels that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring.
outer: for (let i = 0; i < 5; i++) {
doSomething(i);
}
for (let i = 0; i < 5; i++) {
doSomething(i);
}
Disallow Unused Variables
Rule ID: no-unused-vars
Description: Prevents unused variable declarations, which could indicate errors or incomplete refactoring, cluttering the code. An exception exists for variables named _, signaling intentional non-use and maintaining code cleanliness.
function foo() {
const x = 10;
return 5;
}
function foo() {
const x = 10;
return x;
}
Disallow Early Use
Rule ID: no-use-before-define
Description: In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it's possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.
console.log(x);
var x = 1;
var x = 1;
console.log(x);
Disallow unnecessary catch clauses
Rule ID: no-useless-catch
Description: A catch clause that only rethrows the original error is redundant, and has no effect on the runtime behavior of the program. These redundant clauses can be a source of confusion and code bloat, so it's better to disallow these unnecessary catch clauses.
try {
doSomething();
} catch (e) {
throw e;
}
doSomething();
Disallow unnecessary computed property keys in objects and classes
Rule ID: no-useless-computed-key
Description: It's unnecessary to use computed properties with literals such as:
const obj = { ["foo"]: 1 };
const obj = { foo: 1 };
Disallow unnecessary concatenation of strings
Rule ID: no-useless-concat
Description: It's unnecessary to concatenate two strings together, such as:
const s = "a" + "b";
const s = "ab";
Disallow unnecessary constructor
Rule ID: no-useless-constructor
Description: ES2015 provides a default class constructor if one is not specified. As such, it is unnecessary to provide an empty constructor or one that simply delegates into its parent class, as in the following examples:
class A {
constructor() {}
}
class A {}
Disallow unnecessary escape usage
Rule ID: no-useless-escape
Description: Escaping non-special characters in strings, template literals, and regular expressions doesn't have any effect, as demonstrated in the following example:
const s = "\a";
const s = "a";
Disallow renaming import, export, and destructured assignments to the same name
Rule ID: no-useless-rename
Description: ES2015 allows for the renaming of references in import and export statements as well as destructuring assignments. This gives programmers a concise syntax for performing these operations while renaming these references:
const { foo: foo } = obj;
const { foo } = obj;
Disallow redundant return statements
Rule ID: no-useless-return
Description: A return; statement with nothing after it is redundant, and has no effect on the runtime behavior of a function. This can be confusing, so it's better to disallow these redundant statements.
function foo() {
doSomething();
return;
}
function foo() {
doSomething();
}
Require let or const instead of var
Rule ID: no-var
Description: ECMAScript 6 allows programmers to create variables with block scope instead of function scope using the let
var x = 10;
const x = 10;
Disallow use of the void operator.
Rule ID: no-void
Description: The void operator takes an operand and returns undefined: void expression will evaluate expression and return undefined. It can be used to ignore any side effects expression may produce:
void doSomething();
doSomething();
Disallow Warning Comments
Rule ID: no-warning-comments
Description: Developers often add comments to code which is not complete or needs review. Most likely you want to fix or review the code, and then remove the comment, before you consider the code to be production ready.
// TODO: fix this later
function foo() {}
function foo() {}
Disallow whitespace before properties
Rule ID: no-whitespace-before-property
Description: JavaScript allows whitespace between objects and their properties. However, inconsistent spacing can make code harder to read and can lead to errors.
Disallow with statements
Rule ID: no-with
Description: The with statement is potentially problematic because it adds members of an object to the current scope, making it impossible to tell what a variable inside the block actually refers to.
with (obj) {
a = 1;
}
obj.a = 1;
Enforce the location of single-line statements
Rule ID: nonblock-statement-body-position
Description: When writing if, else, while, do-while, and for statements, the body can be a single statement instead of a block. It can be useful to enforce a consistent location for these single statements.
Enforce consistent line breaks inside braces
Rule ID: object-curly-newline
Description: A number of style guides require or disallow line breaks inside of object braces and other tokens.
Enforce consistent spacing inside braces
Rule ID: object-curly-spacing
Description: While formatting preferences are very personal, a number of style guides require
Enforce placing object properties on separate lines
Rule ID: object-property-newline
Description: This rule permits you to restrict the locations of property specifications in object literals. You may prohibit any part of any property specification from appearing on the same line as any part of any other property specification. You may make this prohibition absolute, or, by invoking an object option, you may allow an exception, permitting an object literal to have all parts of all of its property specifications on a single line.
Require Object Literal Shorthand Syntax
Rule ID: object-shorthand
Description: ECMAScript 6 provides a concise form for defining object literal methods and properties. This
const obj = {
foo: foo,
bar: function () { return 1; },
};
const obj = {
foo,
bar() { return 1; },
};
Enforce variables to be declared either together or separately in functions
Rule ID: one-var
Description: Variables can be declared at any point in JavaScript code using var, let, or const. There are many styles and preferences related to the declaration of variables, and one of those is deciding on how many variable declarations should be allowed in a single function.
Require or disallow newlines around variable declarations
Rule ID: one-var-declaration-per-line
Description: Some developers declare multiple var statements on the same line:
Require or disallow assignment operator shorthand where possible
Rule ID: operator-assignment
Description: JavaScript provides shorthand operators that combine variable assignment and some simple mathematical operations. For example, x = x + 4 can be shortened to x += 4. The supported shorthand forms are as follows:
x = x + 4;
x += 4;
Enforce consistent linebreak style for operators
Rule ID: operator-linebreak
Description: When a statement is too long to fit on a single line, line breaks are generally inserted next to the operators separating expressions. The first style coming to mind would be to place the operator at the end of the line, following the English punctuation rules.
Require or disallow padding within blocks
Rule ID: padded-blocks
Description: Some style guides require block statements to start and end with blank lines. The goal is
Require or disallow padding lines between statements
Rule ID: padding-line-between-statements
Description: This rule requires or disallows blank lines between the given 2 kinds of statements.
Require using arrow functions for callbacks
Rule ID: prefer-arrow-callback
Description: Arrow functions can be an attractive alternative to function expressions for callbacks or function arguments.
arr.map(function (x) {
return x * 2;
});
arr.map((x) => x * 2);
Suggest using const
Rule ID: prefer-const
Description: If a variable is never reassigned, using the const declaration is better.
let x = 10;
console.log(x);
const x = 10;
console.log(x);
Prefer destructuring from arrays and objects
Rule ID: prefer-destructuring
Description: With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called destructuring. This rule enforces usage of destructuring instead of accessing a property through a member expression.
const foo = obj.foo;
const { foo } = obj;
Disallow the use of Math.pow in favor of the ** operator
Rule ID: prefer-exponentiation-operator
Description: Introduced in ES2016, the infix exponentiation operator ** is an alternative for the standard Math.pow function.
const result = Math.pow(2, 8);
const result = 2 ** 8;
Suggest using named capture group in regular expression
Rule ID: prefer-named-capture-group
Description: With the landing of ECMAScript 2018, named capture groups can be used in regular expressions, which can improve their readability.
const re = /(\d{4})-(\d{2})/;
const re = /(?<year>\d{4})-(?<month>\d{2})/;
Prefer use of an object spread over Object.assign
Rule ID: prefer-object-spread
Description: When Object.assign is called using an object literal as the first argument, this rule requires using the object spread syntax instead. This rule also warns on cases where an Object.assign call is made using a single argument that is an object literal, in this case, the Object.assign call is not needed.
const merged = Object.assign({}, source);
const merged = { ...source };
Require using Error objects as Promise rejection reasons
Rule ID: prefer-promise-reject-errors
Description: It is considered good practice to only pass instances of the built-in Error object to the reject() function for user-defined errors in Promises. Error objects automatically store a stack trace, which can be used to debug an error by determining where it came from. If a Promise is rejected with a non-Error value, it can be difficult to determine where the rejection occurred.
Promise.reject("something failed");
Promise.reject(new Error("something failed"));
Suggest using Reflect methods where applicable
Rule ID: prefer-reflect
Description: This rule was deprecated in ESLint v3.9.0 and will not be replaced. The original intent of this rule now seems misguided as we have come to understand that Reflect methods are not actually intended to replace the Object counterparts the rule suggests, but rather exist as low-level primitives to be used with proxies in order to replicate the default behavior of various previously existing functionality.
Disallow use of the RegExp constructor in favor of regular expression literals
Rule ID: prefer-regex-literals
Description: There are two ways to create a regular expression:
const re = new RegExp("abc");
const re = /abc/;
Suggest using the rest parameters instead of arguments
Rule ID: prefer-rest-params
Description: There are rest parameters in ES2015.
function sum() {
return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0);
}
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
Suggest using template literals instead of string concatenation.
Rule ID: prefer-template
Description: In ES2015 (ES6), we can use template literals instead of string concatenation.
const greeting = "Hello, " + name + "!";
const greeting = `Hello, ${name}!`;
Require quotes around object literal property names
Rule ID: quote-props
Description: Object literal property names can be defined in two ways: using literals or using strings. For example, these two objects are equivalent:
Enforce the consistent use of either backticks, double, or single quotes
Rule ID: quotes
Description: JavaScript allows you to define strings in one of three ways: double quotes, single quotes, and backticks (as of ECMAScript 6). For example:
Require Radix Parameter
Rule ID: radix
Description: When using the parseInt() function it is common to omit the second argument, the radix, and let the function try to determine from the first argument what type of number it is. By default, parseInt() will autodetect decimal and hexadecimal (via 0x prefix). Prior to ECMAScript 5, parseInt() also autodetected octal literals, which caused problems because many developers assumed a leading 0 would be ignored.
const n = parseInt("071");
const n = parseInt("071", 10);
Detect inline styles in Components
Rule ID: react-native/no-inline-styles
Description: It's (subjectively) good practice to separate styles from the view layout, when possible. This rule detects inline style objects when they contain literal values. If inline styles only contain variable values, the style is considered acceptable because it's sometimes necessary to set styles based on state or props.
function Box() {
return <View style={{ height: 10, width: 10 }} />;
}
const styles = StyleSheet.create({ box: { height: 10, width: 10 } });
function Box() {
return <View style={styles.box} />;
}
Avoid Single Element Style Arrays
Rule ID: react-native/no-single-element-style-arrays
Description: Using single element style arrays cause unnecessary re-renders as each time the array's identity changes.
function Box() {
return <View style={[styles.box]} />;
}
function Box() {
return <View style={styles.box} />;
}
Disallow assignments that can lead to race conditions due to usage of await or yield
Rule ID: require-atomic-updates
Description: When writing asynchronous code, it is possible to create subtle race condition bugs. Consider the following example:
Disallow async functions which have no await expression
Rule ID: require-await
Description: Asynchronous functions in JavaScript behave differently than other functions in two important ways:
async function getValue() {
return 42;
}
async function getValue() {
return await fetchValue();
}
Require JSDoc comments
Rule ID: require-jsdoc
Description: This rule was deprecated in ESLint v5.10.0.
Enforce the use of u flag on RegExp
Rule ID: require-unicode-regexp
Description: RegExp u flag has two effects:
const re = /abc/;
const re = /abc/u;
Disallow generator functions that do not have yield
Rule ID: require-yield
Description: This rule generates warnings for generator functions that do not have the yield keyword.
function* gen() {
return 10;
}
function* gen() {
yield 10;
}
Enforce spacing between rest and spread operators and their expressions
Rule ID: rest-spread-spacing
Description: ES2015 introduced the rest and spread operators, which expand an iterable structure into its individual parts. Some examples of their usage are as follows:
Require or disallow semicolons instead of ASI
Rule ID: semi
Description: JavaScript is unique amongst the C-like languages in that it doesn't require semicolons at the end of each statement. In many cases, the JavaScript engine can determine that a semicolon should be in a certain spot and will automatically add it. This feature is known as automatic semicolon insertion (ASI) and is considered one of the more controversial features of JavaScript. For example, the following lines are both valid:
Enforce spacing before and after semicolons
Rule ID: semi-spacing
Description: JavaScript allows you to place unnecessary spaces before or after a semicolon.
Enforce location of semicolons
Rule ID: semi-style
Description: Generally, semicolons are at the end of lines. However, in semicolon-less style, semicolons are at the beginning of lines. This rule enforces that semicolons are at the configured location.
Import Sorting
Rule ID: sort-imports
Description: The import statement is used to import members (functions, objects or primitives) that have been exported from an external module. Using a specific member syntax:
Require object keys to be sorted
Rule ID: sort-keys
Description: When declaring multiple properties, some developers prefer to sort property names alphabetically to be able to find necessary property easier at the later time. Others feel that it adds complexity and becomes burden to maintain.
Variable Sorting
Rule ID: sort-vars
Description: When declaring multiple variables within the same block, some developers prefer to sort variable names alphabetically to be able to find necessary variable easier at the later time. Others feel that it adds complexity and becomes burden to maintain.
Require Or Disallow Space Before Blocks
Rule ID: space-before-blocks
Description: Consistency is an important part of any style guide.
Require or disallow a space before function parenthesis
Rule ID: space-before-function-paren
Description: When formatting a function, whitespace is allowed between the function name or function keyword and the opening paren. Named functions also require a space between the function keyword and the function name, but anonymous functions require no whitespace. For example:
Disallow or enforce spaces inside of parentheses
Rule ID: space-in-parens
Description: Some style guides require or disallow spaces inside of parentheses:
Require spacing around infix operators
Rule ID: space-infix-ops
Description: While formatting preferences are very personal, a number of style guides require spaces around operators, such as:
Require or disallow spaces before/after unary operators
Rule ID: space-unary-ops
Description: Some style guides require or disallow spaces before or after unary operators. This is mainly a stylistic issue, however, some JavaScript expressions can be written without spacing which makes it harder to read and maintain.
Require or disallow strict mode directives
Rule ID: strict
Description: A strict mode directive is a "use strict" literal at the beginning of a script or function body. It enables strict mode semantics.
Enforce spacing around colons of switch statements
Rule ID: switch-colon-spacing
Description: Spacing around colons improves readability of case/default clauses.
Require symbol description
Rule ID: symbol-description
Description: The Symbol function may have an optional description:
const sym = Symbol();
const sym = Symbol("user id");
Enforce Usage of Spacing in Template Strings
Rule ID: template-curly-spacing
Description: We can embed expressions in template strings with using a pair of ${ and }.
Require or disallow spacing between template tags and their literals
Rule ID: template-tag-spacing
Description: With ES6, it's possible to create functions called tagged template literals where the function parameters consist of a template literal's strings and expressions.
Enforce valid JSDoc comments
Rule ID: valid-jsdoc
Description: This rule was deprecated in ESLint v5.10.0.
Enforce comparing typeof expressions against valid strings
Rule ID: valid-typeof
Description: For a vast majority of use cases, the result of the typeof operator is one of the following string literals: "undefined", "object", "boolean", "number", "string", "function", "symbol", and "bigint". It is usually a typing mistake to compare the result of a typeof operator to other string literals.
if (typeof x === "strnig") {
doSomething();
}
if (typeof x === "string") {
doSomething();
}
Require Variable Declarations to be at the top of their scope
Rule ID: vars-on-top
Description: The vars-on-top rule generates warnings when variable declarations are not used serially at the top of a function scope or the top of a program.
function foo() {
bar();
var x = 1;
return x;
}
function foo() {
var x = 1;
bar();
return x;
}
Require IIFEs to be Wrapped
Rule ID: wrap-iife
Description: You can immediately invoke function expressions, but not function declarations. A common technique to create an immediately-invoked function expression (IIFE) is to wrap a function declaration in parentheses. The opening parentheses causes the contained function to be parsed as an expression, rather than a declaration.
var result = function () {
return 42;
}();
var result = (function () {
return 42;
})();
Require Regex Literals to be Wrapped
Rule ID: wrap-regex
Description: When a regular expression is used in certain situations, it can end up looking like a division operator. For example:
function f() {
return /foo/.test(str);
}
function f() {
return (/foo/).test(str);
}
Enforce spacing around the * in yield* expressions
Rule ID: yield-star-spacing
Description: This rule enforces spacing around the * in "yield*" expressions.
Require or disallow Yoda Conditions
Rule ID: yoda
Description: Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:
if ("red" === color) {
stop();
}
if (color === "red") {
stop();
}
Security
Cyclopt scans your JavaScript code for security vulnerabilities, injection, insecure configuration, weak cryptography, data exposure, and more. Each finding below lists its Rule ID, what it detects and how to fix it, a severity, and the relevant CWE/OWASP classification.
Detect Angular Element Methods
Rule ID: detect-angular-element-methods
Description: angular.element(...).$SINK(...) writes its argument into the live DOM, so any controller-scope value that leaks in will be parsed as HTML and can run script. Contextually encode the value before it reaches $SINK, or route it through $sce.getTrustedHtml / $sanitize when raw markup must be preserved.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Detect Angular Element Taint
Rule ID: detect-angular-element-taint
Description: Reflected URL data (location/hash/search/$http response) is flowing into angular.element(...).$SINK(...), which interprets the value as HTML and enables DOM-XSS. Encode the value at the point of insertion, or wrap it with $sce.getTrustedHtml / $sanitize if the markup must remain intact.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Detect Angular Sce Disabled
Rule ID: detect-angular-sce-disabled
Description: Strict Contextual Escaping has been turned off via $sceProvider.enabled(false). With SCE disabled, AngularJS no longer treats interpolated bindings as untrusted, broadening the XSS attack surface of the application. Leave SCE enabled and use $sce.trustAs* only for vetted values.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Detect Angular Trust As Method
Rule ID: detect-angular-trust-as-method
Description: Scope data is being wrapped with $sce.trustAs / $sce.trustAsHtml, which marks it as exempt from Angular's contextual escaping. If any of that data originates from a user, the trust label lets it run as HTML or script. Validate the value first and avoid trusting raw scope properties wholesale.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Unsafe Argon2 Config
Rule ID: unsafe-argon2-config
Description: Argon2id is the variant recommended by RFC 9106 for password hashing because it combines the side-channel resistance of Argon2i with the GPU-cracking resistance of Argon2d. This argon2.hash call selects a different variant, weakening protection in environments where an attacker can probe cache timings or apply parallel hardware. Pass { type: argon2.argon2id } unless you have a documented reason to choose otherwise.
CWE: CWE-916 · OWASP: A02:2021, A04:2025
Detect Child Process
Rule ID: detect-child-process
Description: A child_process API (exec, execSync, spawn, or spawnSync) is invoked with a command derived from the Lambda $EVENT payload. Any caller of the function can then choose what binary runs on the host, turning the handler into a remote shell. Pass a fixed executable path and put user input only in the args array of spawn, with an allow-list of permitted values.
CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025
Dynamodb Request Object
Rule ID: dynamodb-request-object
Description: The Lambda $EVENT object is flowing straight into a DynamoDB operation (query, scan, put, update, delete, transactWrite, executeStatement, etc.). Caller-controlled keys such as TableName, KeyConditionExpression, or FilterExpression can be rewritten to read or mutate items the function should never touch. Construct the request parameters from individually validated fields rather than spreading the event payload.
CWE: CWE-943 · OWASP: A01:2017
Knex Sqli
Rule ID: knex-sqli
Description: Knex's raw-SQL helpers (raw, fromRaw, whereRaw) are being given a string built from Lambda $EVENT data, which bypasses Knex's query builder and lets the caller inject arbitrary SQL. Move the user-supplied value into the bindings array, e.g. knex.raw('SELECT * FROM t WHERE id = ?', [userInput]), so Knex parameterizes it for the driver.
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Mysql Sqli
Rule ID: mysql-sqli
Description: A mysql/mysql2 query() or execute() call is being passed a SQL string assembled from the Lambda event, so an attacker controls the query text and can read or modify any table the connection has rights to. Always provide the SQL as a fixed string with ? placeholders and pass user values as the second argument, for example pool.execute('SELECT * FROM t WHERE id = ?', [id]).
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Pg Sqli
Rule ID: pg-sqli
Description: The query text handed to node-postgres client.query() is being concatenated from the Lambda $EVENT, so the caller can append ; and run additional statements or rewrite the existing one. Switch to positional parameters such as client.query('SELECT * FROM t WHERE id = $1', [id]) so pg sends the value separately from the SQL.
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Sequelize Sqli
Rule ID: sequelize-sqli
Description: Untrusted Lambda input is reaching sequelize.query() as part of the SQL string itself, so the ORM's escaping is sidestepped and the query becomes attacker-shaped. Keep the SQL literal and pass the user value through replacements or bind, e.g. sequelize.query('SELECT * FROM t WHERE status = ?', { replacements: [status], type: QueryTypes.SELECT }).
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Tainted Eval
Rule ID: tainted-eval
Description: Data from the Lambda $EVENT is being executed as JavaScript via eval() or the Function constructor. Whatever runs through that sink has full access to the handler's process, environment variables, and IAM credentials, so the function effectively delegates code execution to its callers. Parse the input as data (e.g. JSON.parse) or dispatch via a fixed lookup table instead of evaluating it.
CWE: CWE-95 · OWASP: A03:2021, A05:2025
Tainted HTML Response
Rule ID: tainted-html-response
Description: An HTML response body returned from this Lambda is built from the incoming $EVENT, so the caller can place arbitrary markup and <script> payloads into a page that downstream clients trust. Render through a templating engine that escapes by default, or HTML-encode the dynamic fragments (e.g. via he.encode) before embedding them in the body.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Tainted HTML String
Rule ID: tainted-html-string
Description: Markup is being assembled by hand via +, concat, util.format, or a template literal, with a value that originated in the Lambda event. Anything the caller puts in that variable lands in the DOM verbatim and becomes a stored or reflected XSS payload. Use a templating library that escapes interpolations, or wrap each dynamic piece with an HTML-encoding helper before concatenation.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Tainted SQL String
Rule ID: tainted-sql-string
Description: String concatenation or template literals are gluing Lambda event data into a SQL statement containing SELECT/INSERT/UPDATE/DELETE/CREATE/ALTER/DROP. Any client driver that later executes this string will run whatever syntax the caller injected, exposing the database to read or write attacks. Build the query as a parameterized statement, or delegate to an ORM such as Sequelize that binds values separately from SQL text.
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Vm Runincontext Injection
Rule ID: vm-runincontext-injection
Description: Node's vm module (runInContext, runInNewContext, runInThisContext, compileFunction, new Script, new SourceTextModule) is being asked to execute a source string derived from the Lambda event. The vm API is an isolation tool, not a sandbox; once attacker-controlled code runs inside it, escaping back into the host process is trivial. Treat the input as data and parse it explicitly rather than feeding it to a vm entry point.
CWE: CWE-94 · OWASP: A03:2021, A05:2025
Tofastproperties Code Execution
Rule ID: tofastproperties-code-execution
Description: Bluebird's toFastProperties internally hands its argument to eval(). Whatever flows in there is executed as JavaScript, so any tainted value reaching this helper becomes arbitrary code execution. Pass only trusted, controlled objects to this utility.
CWE: CWE-94 · OWASP: A03:2021, A05:2025
Dom Based XSS
Rule ID: dom-based-xss
Description: Pieces of document.location are being fed straight into document.write(...), so anything an attacker appends to the URL is parsed as HTML and injected into the page. A crafted link such as ?default=<script>alert(1)</script> is enough to land script execution. Build the DOM through safe APIs (textContent, createElement) and validate URL parameters against an allow-list.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Eval Detected
Rule ID: eval-detected
Description: A non-literal expression is being handed to eval(...). Once any portion of that string traces back to untrusted input, the runtime will execute attacker-controlled JavaScript. Rework the logic to call the intended function directly or parse the data with JSON.parse.
CWE: CWE-95 · OWASP: A03:2021, A05:2025
Insecure Innerhtml
Rule ID: insecure-innerhtml
Description: Assigning a dynamic value to $EL.innerHTML lets any HTML or <script> content in the value execute inside the page. Build the nodes programmatically with textContent / createElement, or run the markup through DOMPurify before assigning.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Js Open Redirect
Rule ID: js-open-redirect
Description: A query-string or hash value pulled from the current URL is being assigned to location.href / location.replace, so the page will follow whatever destination the original link encoded. Attackers can use this for phishing or to deliver javascript: payloads. Validate the redirect target against a known-good allow-list before navigating.
CWE: CWE-601 · OWASP: A01:2021, A01:2025
Js Open Redirect From Function
Rule ID: js-open-redirect-from-function
Description: A function parameter $PROP propagates into location.href / location.replace, giving callers full control over where the window navigates. Beyond classic open redirects, a value such as javascript:... will execute as script. Compare the destination against an allow-list of safe paths before assignment.
CWE: CWE-601 · OWASP: A01:2021, A01:2025
Raw HTML Concat
Rule ID: raw-html-concat
Description: Tag fragments such as <div ... are being concatenated together with location data, which produces an unescaped HTML string. Once that string is rendered, the URL contents are parsed as markup and can run script. Assemble nodes via the DOM API or sanitize the value with DOMPurify before producing HTML.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Raw HTML Join
Rule ID: raw-html-join
Description: An array containing raw HTML fragments (e.g. <div ... / ... </div>) is being assembled with Array.prototype.join(...). If any element of that array carries user input, the joined string becomes a live XSS sink as soon as it is inserted into the DOM. Build the markup with DOM APIs or sanitize each fragment before joining.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Chrome Remote Interface Compilescript Injection
Rule ID: chrome-remote-interface-compilescript-injection
Description: Tainted input is flowing into a chrome-remote-interface sink such as Runtime.compileScript, Runtime.evaluate, Page.navigate, Runtime.printToPDF or Page.setDocumentContent. These APIs drive a real browser, so attacker-supplied scripts, URLs or HTML can trigger SSRF or in-page code execution. Validate and restrict these values against an explicit allow-list before invoking the DevTools client.
CWE: CWE-918 · OWASP: A10:2021, A01:2025
Deno Dangerous Run
Rule ID: deno-dangerous-run
Description: Deno.run is being launched with a cmd array whose program name or shell argument comes from a function parameter rather than a literal. When the executable resolves to sh/bash/zsh and the next token is -c, the third element is interpreted as shell script, so a caller can chain arbitrary commands. Pin the executable to a constant path and pass user data as separate args without a shell wrapper.
CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025
CORS Misconfiguration
Rule ID: cors-misconfiguration
Description: Access-Control-Allow-Origin is being assigned from request data (query/body/params/headers/cookies). Reflecting whatever origin the caller asks for effectively turns CORS off and lets any site act as a trusted origin. Match against a fixed allow-list of origins instead.
CWE: CWE-346 · OWASP: A07:2021, A07:2025
Direct Response Write
Rule ID: direct-response-write
Description: Request data is being piped straight into res.write(...) or res.send(...) without an explicit non-HTML Content-Type or escaping. Anything HTML-shaped in the payload will be parsed by the browser as markup, yielding reflected XSS. Render through a template engine or sanitize the value (e.g. DOMPurify) before sending.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Express Check Directory Listing
Rule ID: express-check-directory-listing
Description: The serve-index middleware is mounted on this Express app, which renders a browsable index of any directory it serves. That exposes file names, sizes, and modification times that often reveal backups, configuration, or stale endpoints. Remove the middleware unless the directory is intentionally public, and make sure sensitive files are blocked from being listed.
CWE: CWE-548 · OWASP: A06:2017, A01:2021, A01:2025
Express Cookie Session Default Name
Rule ID: express-cookie-session-default-name
Description: express-session / cookie-session is being initialised without a custom name, so the cookie keeps its default identifier (connect.sid). That default acts as a server fingerprint, telling attackers which middleware is in use and which CVEs to try. Pick a neutral, project-specific cookie name in the session options.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Express Cookie Session No Domain
Rule ID: express-cookie-session-no-domain
Description: No cookie.domain attribute is being passed to the session middleware. Leaving the domain implicit can cause the cookie to be sent to unintended hosts (or, conversely, fail to scope to the expected ones). Set domain explicitly so the browser only attaches the session to the right origin.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Express Cookie Session No Expires
Rule ID: express-cookie-session-no-expires
Description: No cookie.expires (or equivalent maxAge) was supplied to the session middleware, so the session cookie defaults to a session-only or unbounded lifetime depending on the library. Long-lived, unexpiring tokens give a stolen cookie indefinite reuse. Specify an explicit expiration that matches the application's session policy.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Express Cookie Session No Httponly
Rule ID: express-cookie-session-no-httponly
Description: Without cookie.httpOnly: true, the session cookie remains readable from document.cookie. A single XSS sink elsewhere in the app is then enough for an attacker to exfiltrate the session token. Always set httpOnly so client-side scripts cannot reach the value.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Express Cookie Session No Path
Rule ID: express-cookie-session-no-path
Description: The session middleware has no cookie.path defined. Without a path scope, the cookie is attached to every request under the origin, including routes (e.g. third-party static apps) where it should not be readable. Set path so the cookie is only sent to the application paths that need it.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Express Cookie Session No Secure
Rule ID: express-cookie-session-no-secure
Description: The session middleware is configured without cookie.secure: true, meaning the browser will happily send the session identifier over plain HTTP. Anyone able to observe the network (open Wi-Fi, MITM, mixed-content downgrade) can lift the cookie and hijack the session. Enable secure so the cookie is restricted to HTTPS.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Express Expat Xxe
Rule ID: express-expat-xxe
Description: Request input is reaching node-expat's .parse(...) / .write(...) API. Because expat happily expands internal and external entity declarations, a crafted XML body can read local files, contact internal services, or stage a billion-laughs DoS. Reject DTDs at the application layer or move to a parser that refuses entities by default.
CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025
Express Insecure Template Usage
Rule ID: express-insecure-template-usage
Description: A template engine compile/render call (pug, ejs, handlebars, nunjucks, etc.) is receiving its template source from $REQ. When the engine compiles attacker-controlled markup, expressions inside the template execute on the server — a Server-Side Template Injection that frequently grades up to full RCE. Treat templates as code: store them on disk and pass user data only as the rendering context.
CWE: CWE-1336 · OWASP: A03:2021, A01:2017, A05:2025
Express JWT Not Revoked
Rule ID: express-jwt-not-revoked
Description: express-jwt is being mounted without an isRevoked callback, so the server has no way to invalidate a token before it naturally expires. If a JWT is leaked (logs, browser history, stolen device), it stays valid until expiry. Provide an isRevoked function backed by a denylist or token version check.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Express Libxml Noent
Rule ID: express-libxml-noent
Description: libxmljs.parseXml(...) is being called with noent: true while parsing a request payload, which tells libxml to expand external entities. An attacker can then post a DOCTYPE that pulls in local files or triggers SSRF (classic XXE). Drop the noent option (or set it to false) so entity references are not resolved.
CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025
Express Open Redirect
Rule ID: express-open-redirect
Description: res.redirect(...) is being called with a destination assembled from $REQ (query/body/params/etc.), so the route will follow whatever URL an attacker supplies. This is a classic open-redirect primitive used in phishing and OAuth-step abuse. Compare the target against an allow-list of trusted URLs before redirecting, or show a confirmation interstitial.
CWE: CWE-601 · OWASP: A01:2021, A01:2025
Express Path Join Resolve Traversal
Rule ID: express-path-join-resolve-traversal
Description: A request-controlled segment is being fed into path.join(...) or path.resolve(...). Sequences such as ../ allow the caller to escape the intended directory and read or write arbitrary files. After joining, canonicalise the result and assert that it still lives under the expected base directory.
CWE: CWE-22 · OWASP: A05:2017, A01:2021, A01:2025
Express Phantom Injection
Rule ID: express-phantom-injection
Description: The PhantomJS page object (page.open, page.openUrl, page.setContent, page.evaluateJavaScript, page.property('content', ...)) is being driven with request data, so an attacker can point the headless browser anywhere — including intranet hosts and file:// URLs (SSRF), or inject script via evaluateJavaScript. Restrict the navigation target to a fixed allow-list before invoking the page API.
CWE: CWE-918 · OWASP: A10:2021, A01:2025
Express Puppeteer Injection
Rule ID: express-puppeteer-injection
Description: Calls like page.goto, page.setContent, page.evaluate*, or page.evaluateOnNewDocument are being fed values coming from $REQ. That lets the requester steer the headless Chromium instance toward internal targets (SSRF) and, for the evaluate family, run arbitrary JavaScript inside the rendered page. Pin the URL and any in-page scripts to constants and treat user input as data only.
CWE: CWE-918 · OWASP: A10:2021, A01:2025
Express Res Sendfile
Rule ID: express-res-sendfile
Description: Untrusted request data is being handed directly to res.sendFile(...). Because the handler does not constrain the path, an attacker can supply traversal sequences (e.g. ../../etc/passwd) and exfiltrate arbitrary files from the server. Resolve the path, then verify it remains inside the allowed root and pass root / dotfiles options to sendFile.
CWE: CWE-73 · OWASP: A04:2021, A06:2025
Express Sandbox Code Injection
Rule ID: express-sandbox-code-injection
Description: A sandbox instance's .run(...) is being invoked with request-derived input. The library is a sandboxed JavaScript evaluator, so handing it untrusted source code executes that code on the server and, given known sandbox escapes, can break out into the host process. Never pass user-supplied strings to sandbox.run.
CWE: CWE-94 · OWASP: A03:2021, A05:2025
Express Session Hardcoded Secret
Rule ID: express-session-hardcoded-secret
Description: The express-session middleware is being initialised with a string-literal secret. A signing key that lives in source ships with every clone of the repo, ends up in build artefacts, and cannot be rotated without a code change. Load the secret from an environment variable or a managed secret store and inject it at runtime.
CWE: CWE-798 · OWASP: A07:2021, A07:2025
Express SSRF
Rule ID: express-ssrf
Description: A request.$METHOD(...) call is being built out of values pulled from $REQ, letting the caller pick both the host and protocol of the outbound HTTP request. Attackers exploit this for SSRF — pivoting to internal services, cloud metadata endpoints, or file:// URLs. Keep the base URL fixed in code and only let user input populate path/query parameters after validation.
CWE: CWE-918 · OWASP: A10:2021, A01:2025
Express Third Party Object Deserialization
Rule ID: express-third-party-object-deserialization
Description: node-serialize / serialize-to-js exposes unserialize / deserialize calls that will run any JavaScript embedded in the payload they parse — feeding them request data is equivalent to handing the attacker an RCE primitive. Switch to safe formats such as JSON.parse for objects or Buffer.from for binary input.
CWE: CWE-502 · OWASP: A08:2017, A08:2021, A08:2025
Express Vm Injection
Rule ID: express-vm-injection
Description: Built-in vm helpers (runInContext, runInNewContext, runInThisContext, compileFunction, new vm.Script) are being given source pulled from $REQ. The vm module is not a security boundary — code passed to it runs with the full Node process privileges, so this is a direct RCE sink. Avoid evaluating user-provided code entirely.
CWE: CWE-94 · OWASP: A03:2021, A05:2025
Express Vm2 Injection
Rule ID: express-vm2-injection
Description: vm2 constructors (new VM, new NodeVM, new VMScript) and their .run(...) outputs are being instantiated with request data. The package has a documented history of sandbox-escape CVEs, and the project is now unmaintained — code that reaches the sandbox should be assumed to run with full host privileges. Refuse to evaluate user-supplied scripts, or use a language-level interpreter you control.
CWE: CWE-94 · OWASP: A03:2021, A05:2025
Express Wkhtmltoimage Injection
Rule ID: express-wkhtmltoimage-injection
Description: The URL/markup passed to wkhtmltoimage.generate(...) originates from $REQ. Because wkhtmltoimage fetches resources to render them, an attacker can make the server hit internal hosts, file:// resources, or cloud metadata endpoints — a server-side request forgery primitive disguised as a PDF render. Restrict the input to a vetted set of URLs.
CWE: CWE-918 · OWASP: A10:2021, A01:2025
Express Wkhtmltopdf Injection
Rule ID: express-wkhtmltopdf-injection
Description: wkhtmltopdf(...) is being called with a destination coming from request data. The PDF renderer will load whatever URL it receives, which makes it a convenient SSRF vector — internal services and file:// URLs are both reachable. Limit the input to URLs you trust before generating the document.
CWE: CWE-918 · OWASP: A10:2021, A01:2025
Express Xml2json Xxe
Rule ID: express-xml2json-xxe
Description: xml2json.toJson(...) is receiving XML that originated in the request. By default the underlying parser resolves DTDs and entity references, so a malicious payload can read local files or pivot to internal URLs through XXE. Validate that no DOCTYPE is present, or switch to a parser configured to refuse entities outright.
CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025
Express Xml2json Xxe Event
Rule ID: express-xml2json-xxe-event
Description: xml2json.toJson(...) is being invoked from inside a req.on(...) data handler with the streamed request body. Because xml2json does not disable external/internal entity resolution by default, an XXE payload in the stream can read local files or trigger SSRF. Validate the document and use a parser configured to refuse DTDs.
CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025
Raw HTML Format
Rule ID: raw-html-format
Description: A template literal or "<tag ..." + ... / util.format(...) concatenation is splicing request data into raw HTML. The resulting string contains attacker-controlled bytes inside markup, which the browser will parse as elements and scripts — a textbook reflected XSS. Build the HTML through a template engine or pass the value through DOMPurify before it joins the markup.
CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025
Remote Property Injection
Rule ID: remote-property-injection
Description: Bracket notation ($OBJ[index] = ...) is being assigned with an index that traces back to request data. The caller can therefore overwrite any property — including __proto__ or constructor — and pivot to prototype pollution. Use literal property names, or look the key up in an explicit allow-list before assignment.
CWE: CWE-522 · OWASP: A02:2017, A04:2021, A06:2025
Require Request
Rule ID: require-request
Description: A dynamic require($SINK) is being resolved with a value supplied by the caller, which lets an attacker pick which module Node loads — including locally available modules with dangerous side effects or local paths that disclose data. Map a finite list of allowed identifiers to literal require calls instead.
CWE: CWE-706 · OWASP: A01:2021, A01:2025
Res Render Injection
Rule ID: res-render-injection
Description: The first argument to res.render(...) — the template name — is being derived from request data, which lets a caller select arbitrary view files. Traversal sequences such as ../folder/index then expose templates that should never be reachable for that user. Restrict the value to a fixed mapping of allowed view names.
CWE: CWE-706 · OWASP: A01:2021, A01:2025
Tainted SQL String
Rule ID: tainted-sql-string
Description: Request data is being glued to a string fragment that starts with SELECT / INSERT / UPDATE / DELETE / CREATE / ALTER / DROP, producing a hand-built SQL statement. Concatenating user input into SQL exposes the query to injection, letting an attacker exfiltrate or mutate database contents. Use parameter binding (? / $1) or an ORM such as Sequelize/Prisma instead.
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
X Frame Options Misconfiguration
Rule ID: x-frame-options-misconfiguration
Description: The value sent for the X-Frame-Options response header is being assigned from request data. Because the caller controls that header, the page's framing policy effectively switches off and clickjacking protections vanish. Set X-Frame-Options to a fixed DENY or SAMEORIGIN value (and prefer a strict Content-Security-Policy: frame-ancestors).
CWE: CWE-451 · OWASP: A04:2021, A06:2025
Hardcoded JWT Secret
Rule ID: hardcoded-jwt-secret
Description: The signing or verification key passed to jose's JWT.sign/JWT.verify is a string literal embedded in the source. Anyone with read access to the repository (CI logs, forks, leaked backups) can forge tokens that the application will accept as authentic. Load the key from an environment variable, AWS Secrets Manager, or a KMS/HSM-backed source so it can be rotated without a code change.
CWE: CWE-798 · OWASP: A07:2021, A07:2025
JWT None Alg
Rule ID: jwt-none-alg
Description: Verification is being performed with JWK.None, which tells jose to accept tokens whose alg header is "none" and therefore carry no signature at all. Any caller can hand the application a forged token with claims of their choosing and it will be treated as valid. Replace JWK.None with the real public/secret key and require a concrete algorithm such as RS256 or HS256.
CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025
Hardcoded JWT Secret
Rule ID: hardcoded-jwt-secret
Description: A literal string is being used as the secret in jsonwebtoken's sign() or verify() call. That secret is the only thing standing between an attacker and a forged session token, and storing it in source means it ships in every build artefact, git history entry, and CI log. Read it from a runtime configuration source (environment variable, parameter store, KMS) and rotate it without touching the codebase.
CWE: CWE-798 · OWASP: A07:2021, A07:2025
JWT Decode Without Verify
Rule ID: jwt-decode-without-verify
Description: jsonwebtoken.decode() returns the claims from a token without checking the signature, and no matching verify() call exists in this scope. Reading user identity, roles, or expiry from an unverified token means trusting whatever the client put in the payload, which is forgeable offline. Use jwt.verify(token, key, options) and consume the claims it returns, keeping decode only for diagnostics on already-trusted tokens.
CWE: CWE-345 · OWASP: A08:2021, A08:2025
JWT None Alg
Rule ID: jwt-none-alg
Description: jsonwebtoken.verify is permitting alg: none in its accepted algorithms list. An attacker can craft an unsigned token with alg: none and have it pass verification. Pin to a concrete algorithm such as HS256 or RS256 and reject everything else.
CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025
JWT Simple Noverify
Rule ID: jwt-simple-noverify
Description: Calling jwt-simple.decode(token, secret, true) (or with a truthy third argument) tells the library to skip signature checking entirely and just return the claims. That turns the token into an unauthenticated client payload, so attackers can mint any identity they like. Drop the noverify flag, or pass false, so the signature is validated against the secret.
CWE: CWE-287, CWE-345, CWE-347 · OWASP: A05:2021, A07:2021, A02:2025, A07:2025
Code String Concat
Rule ID: code-string-concat
Description: Request-derived values from Express handlers or Next.js routers are being passed into eval, which compiles and runs the string as JavaScript with full process privileges. An attacker who can influence the query, body, params or headers can execute arbitrary code on the server. Replace eval with a dedicated parser or a tightly scoped function lookup.
CWE: CWE-95 · OWASP: A03:2021, A05:2025
Dangerous Spawn Shell
Rule ID: dangerous-spawn-shell
Description: A 'child_process.spawn'/'spawnSync' call is launching a shell ('sh', 'bash', 'zsh', etc.) with '-c' and a non-literal argument. When the argument is built from external input the shell parses metacharacters like ';' and '' ' '', turning the call into arbitrary command execution. Invoke the target binary directly with a fixed argv list instead of spawning a shell.
CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025
Detect Eval With Expression
Rule ID: detect-eval-with-expression
Description: Values pulled from location.href, location.hash, location.search or URLSearchParams on them are flowing into eval, new Function, setTimeout or setInterval. Because the URL is fully attacker-controllable, this becomes a same-origin XSS sink: a crafted link compiles and runs arbitrary JavaScript in the victim's session. Parse the URL into typed values and dispatch on a fixed code path instead of evaluating the string.
CWE: CWE-95 · OWASP: A03:2021, A05:2025
Detect Non Literal Fs Filename
Rule ID: detect-non-literal-fs-filename
Description: Function parameter $ARG is reaching an fs/fs/promises API as the path argument. Without validation an attacker can supply ../ segments or absolute paths and read or overwrite files outside the intended directory. Resolve the path and verify it stays within an expected base directory before handing it to fs.
CWE: CWE-22 · OWASP: A05:2017, A01:2021, A01:2025
Detect Non Literal Regexp
Rule ID: detect-non-literal-regexp
Description: A RegExp constructor is being built from a runtime value ($ARG) rather than a literal pattern. An attacker who can influence that string can craft a pathological pattern that pins the V8 regex engine on the main event loop, halting the whole Node process (ReDoS). Prefer hard-coded regex literals, or pre-screen dynamic patterns with a checker such as recheck.
CWE: CWE-1333 · OWASP: A05:2021, A06:2017, A02:2025
Detect Non Literal Require
Rule ID: detect-non-literal-require
Description: require() is being invoked with a variable rather than a string literal. Because require resolves and immediately executes the loaded module, an attacker who controls that variable can load arbitrary code (including paths into node_modules they have written to, or relative paths that escape the project root). Restrict module loading to a fixed list of known module names.
CWE: CWE-95 · OWASP: A03:2021, A05:2025
Detect Redos
Rule ID: detect-redos
Description: Static analysis of pattern $REDOS shows nested or overlapping quantifiers that admit catastrophic backtracking. A short adversarial input can therefore spike CPU on the regex engine and freeze the Node main thread. Rewrite the pattern to remove ambiguous alternation (or switch to a backtracking-free matcher such as re2).
CWE: CWE-1333 · OWASP: A05:2021, A06:2017, A02:2025
Insecure Object Assign
Rule ID: insecure-object-assign
Description: Data parsed straight out of JSON.parse is being merged into another object with Object.assign. Because Object.assign copies every enumerable own property of the source, callers can set fields the server never meant to expose — including privileged flags such as isAdmin or internal IDs (mass assignment). Whitelist the specific properties you want to accept before copying them across.
CWE: CWE-601 · OWASP: A01:2021, A01:2025
MD5 Used As Password
Rule ID: md5-used-as-password
Description: The output of crypto.createHash("md5") is being fed into a function whose name mentions "password". MD5 is fast, unsalted by default and trivially brute-forced on modern hardware, so using it for credentials means a leaked hash database is effectively a leaked password database. Switch to a memory-hard password KDF such as bcrypt, scrypt, or argon2.
CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025
Missing Template String Indicator
Rule ID: missing-template-string-indicator
Description: A {...} placeholder appears inside a backtick template literal but is not preceded by $. Without the dollar sign the braces are emitted as literal text instead of being interpolated, which is almost always a typo. Prefix the placeholder with $ so the expression actually runs.
No Stringify Keys
Rule ID: no-stringify-keys
Description: Using the output of JSON.stringify as an object key is unreliable because the resulting string depends on the runtime's property insertion order, which is not guaranteed to be stable across engines or even across mutations of the same object. Two structurally equal objects can produce different keys. Switch to a deterministic serializer such as json-stable-stringify.
Node Knex Sqli
Rule ID: node-knex-sqli
Description: Knex's escape hatches (knex.raw, fromRaw, whereRaw) are receiving a query string that carries data straight from the Express $REQ object. Anything inside that string is treated as literal SQL, so a malicious payload in the query/body/params can rewrite the statement. Pass the user value as a positional binding instead, e.g. knex.raw('SELECT $1 from table', [userinput]).
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Node Mssql Sqli
Rule ID: node-mssql-sqli
Description: Building the SQL passed to request.query(...) of the mssql driver from a non-literal variable lets attacker-supplied characters break out of the intended clause and append their own SQL. Once the statement is composed by concatenation, the server cannot tell data from code. Bind values explicitly with the typed parameter API, for example request.input('USER_ID', mssql.Int, id) and then reference @USER_ID in the query text.
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Node Mysql Sqli
Rule ID: node-mysql-sqli
Description: The query string handed to the $IMPORT connection's query()/execute() is sourced from a function parameter rather than a literal template. Because the driver substitutes ? placeholders server-side, only values passed through that placeholder list are escaped — text spliced directly into the SQL is not. Move user input out of the SQL string and into the second argument so the driver can bind it safely.
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Node Postgres Sqli
Rule ID: node-postgres-sqli
Description: A pg client's query() is being invoked with a SQL string assembled from a non-literal function argument, so untrusted text ends up inside the statement body. Use node-postgres's numbered placeholders and pass the values as the second argument, e.g. client.query('SELECT * FROM table WHERE id = $1', [userinput]), which sends the data over the wire as parameters rather than splicing it into the query.
CWE: CWE-915 · OWASP: A08:2021, A08:2025
Path Join Resolve Traversal
Rule ID: path-join-resolve-traversal
Description: Attacker-controlled input is being concatenated into a path through path.join or path.resolve. Neither function strips .. segments, so an input like ../../etc/passwd happily resolves outside the intended base directory and is then opened by downstream fs calls. After joining, verify the resolved path is still a prefix of the allowed root before using it.
CWE: CWE-22 · OWASP: A05:2017, A01:2021, A01:2025
Prototype Pollution Assignment
Rule ID: prototype-pollution-assignment
Description: A dynamic property assignment of the form obj[key] = value is using a key sourced from another object lookup, with no __proto__ or constructor guard around it. If key ever resolves to __proto__, constructor or prototype, the write lands on Object.prototype and silently affects every object in the runtime. Guard the key explicitly, switch to a Map, or build the target with Object.create(null).
CWE: CWE-915 · OWASP: A08:2021, A08:2025
Prototype Pollution Loop
Rule ID: prototype-pollution-loop
Description: Recursive walks of the form obj = obj[key] inside a for/while/forEach body are a classic deep-merge/deep-assign primitive. When key is __proto__ the cursor steps onto Object.prototype, and any later assignment along that cursor mutates the prototype shared by every object in the program. Filter out __proto__, constructor and prototype keys, or pivot the walk to a Map keyed by trusted strings.
CWE: CWE-915 · OWASP: A08:2021, A08:2025
Aead No Final
Rule ID: aead-no-final
Description: AEAD ciphers (GCM/CCM/OCB/ChaCha20-Poly1305) require a decipher.final() call to verify the authentication tag. Skipping it means tampered ciphertext is accepted as authentic and the AEAD integrity guarantee no longer holds.
CWE: CWE-310 · OWASP: A02:2021, A04:2025
Create De Cipher No Iv
Rule ID: create-de-cipher-no-iv
Description: Legacy crypto.createCipher / crypto.createDecipher derive the key from a password using a weak KDF and produce a deterministic IV for every invocation. Reusing a (key, IV) pair under counter modes like CTR/GCM/CCM destroys both confidentiality and integrity, and weakens every other mode as well. Switch to createCipheriv / createDecipheriv and supply a random IV of the algorithm's expected length per message.
CWE: CWE-1204
Gcm No Tag Length
Rule ID: gcm-no-tag-length
Description: GCM decryption is being set up through createDecipheriv without an authTagLength option, so Node will accept any tag length the caller supplies. A short, attacker-truncated tag is cheap to forge, which lets adversaries craft ciphertexts that pass decipher.final() and ultimately recover the implicit GHASH authentication key. Pass { authTagLength: 16 } (or the exact length your protocol mandates) when constructing the decipher.
CWE: CWE-310 · OWASP: A02:2021, A04:2025
Hardcoded Passport Secret
Rule ID: hardcoded-passport-secret
Description: Passport strategy options (clientSecret, secretOrKey, consumerSecret) are being initialised from a string literal in the source tree. Whoever obtains a copy of the code or its build artefacts can impersonate the application to the identity provider or forge JWTs that the strategy will accept. Resolve these values at startup from environment variables or a managed secret store so they can be rotated independently of releases.
CWE: CWE-798 · OWASP: A07:2021, A07:2025
Calling Set State On Current State
Rule ID: calling-set-state-on-current-state
Description: The setter returned by useState is being invoked with the current state value itself ($Y($X)), which React's bail-out compares with Object.is and discards — no re-render happens. This is almost always a typo for $Y(!$X) or $Y(nextValue). Update the call to pass the new state you actually want.
Express Sequelize Injection
Rule ID: express-sequelize-injection
Description: An Express request value is reaching sequelize.query(...) as part of the SQL string itself. Sequelize only escapes values that travel through its replacements or bind options, so anything concatenated into the query body is interpreted as SQL syntax. Move the user value into replacements: { ... } (or bind: [...]) and reference it with :name/$1 inside the statement.
CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025
Shelljs Exec Injection
Rule ID: shelljs-exec-injection
Description: shelljs.exec(...) is being called with a non-literal argument. ShellJS forwards the entire string to the system shell, so any metacharacter in the input (;, &&, backticks, etc.) becomes a new command running with the privileges of the Node process. Either avoid exec entirely and use a dedicated ShellJS function (shelljs.cp, shelljs.mv, ...), or pass a hard-coded command string with no concatenated inputs.
CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025


