securityAnswer last reviewed July 2026

Say you have to shell out to a command and part of it comes from user input. How do you do that without handing someone command injection?

Strong answers know exactly which child_process APIs launch a shell and defend with argument arrays instead of trying to escape strings.

What an AI-prepared candidate might say

So the danger is user input ending up inside a shell command. Like exec runs the whole command string through a shell, so if you build it with user input, something like exec(`convert ${filename}`), then a filename with shell metacharacters in it can run arbitrary commands. The safer way is spawn or execFile, where you pass the command and its arguments separately as an array, and then the input just gets treated as one argument instead of shell syntax. I'd also validate any user input, and I try not to build command strings by concatenation at all. If there's a native library that does the same job I'd probably just use that and skip the shell entirely. And run the process with least privilege, so even if something goes wrong the damage stays limited. Basically never trust user input in a command line.

Senior
Locked

Exactly where the shell-invoking APIs stop and the direct-exec ones start, why argument arrays close the hole for good, and where shell: true quietly opens it back up.

Unlock the depth
Staff
Locked

What you do when you genuinely can't avoid a shell, why allowlisting beats escaping, and how you hunt down every injection sink in a big codebase.

Unlock the depth
Follow-up chain
Say you have to shell out to a command and part of it comes from user input. How do you do that without handing someone command injection? | NodeBook