Defensive Coding in JavaScript
Learn and practice some techniques for keeping code secure.
StartKey Concepts
Review core concepts you need to learn to master this subject
Dangers of eval
Dangers and Alternatives of exec
Dangers of fs
Module
Dangers of Regular Expressions
JavaScript Strict Mode
Static Code Analysis
Dangers of eval
Dangers of eval
// This user input causes an infinite loop to run
const user_input = "while(true) ;";
eval(user_input);
// This user input closes the application
const user_input = "process.exit(0)";
eval(user_input);
The eval()
function in JavaScript takes a string as an argument and executes it as Javascript source code. Not only is it slow to execute, but bad actors can also inject malicious code into the input string for mischievous reasons. Thus, it’s best never to use it. If you MUST use it, only allow trusted and predetermined input through it. NEVER trust user input.
The functions, setInterval()
, setTimeout()
, and new Function()
use eval()
in their implementations, and should be used with the same caution.
- 1Javascript is susceptible to all sorts of vulnerabilities, allowing bad actors to insert malicious code into Node applications and packages. Defensive programming combats these vulnerabilities, ens…
- 2The eval() function in JavaScript takes a string as an argument and executes it as Javascript source code. …
- 3In this exercise, we will discuss the exec() method, its risks, and alternatives. The exec() …
- 4The file system, or fs, module in Node.js enables file system operations. It gives us access to methods like: - chmod() to change file permissions - mkdir() to cre…
- 5Regular Expressions are used in almost every single programming language to validate whether user input adheres to an expected condition. Attacke…
- 6Now that you have learned about some dangerous functions and regular expressions to avoid, let’s learn about some defensive tools. One of them is JavaScript’s strict mode. Using [strict mode](https…
- 7Static Code Analysis evaluates a code without executing it. A lint, or linter, is a static …
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory