GuardAPI Logo
GuardAPI

Fix Command Injection in Next.js

Command injection in Next.js typically occurs within API routes or Server Actions when unsanitized user input is passed to Node.js 'child_process' functions. If you are concatenating strings into 'exec', you are granting attackers Remote Code Execution (RCE). In a modern stack, this is a critical failure that bypasses all frontend security layers.

The Vulnerable Pattern

import { exec } from 'child_process';

export default async function handler(req, res) { const { domain } = req.query;

// DANGER: Shell metacharacters like ’;’ or ’&&’ can be injected exec(nslookup ${domain}, (err, stdout) => { if (err) return res.status(500).send(err.message); res.status(200).json({ result: stdout }); }); }

The Secure Implementation

The vulnerability stems from using 'exec', which invokes '/bin/sh' (or cmd.exe) to parse the command string. This allows an attacker to append commands using shell operators. The fix is two-pronged: First, replace 'exec' with 'execFile' or 'spawn'. These functions execute the binary directly, treating the second argument strictly as an array of parameters rather than shell commands. Second, implement strict input validation using a whitelist regex to ensure only expected characters (e.g., alphanumeric, dots, hyphens) are processed. Whenever possible, replace shell calls with native Node.js modules like 'dns' or 'fs'.

import { execFile } from 'child_process';

export default async function handler(req, res) { const { domain } = req.query;

// 1. Input Validation: Use a strict allow-list regex if (!/^[a-zA-Z0-9.-]+$/.test(domain)) { return res.status(400).json({ error: ‘Invalid domain format’ }); }

// 2. Use execFile: It does not spawn a shell, preventing command chaining // Arguments are passed as an array and treated as literals execFile(‘nslookup’, [domain], (err, stdout) => { if (err) return res.status(500).json({ error: ‘Command execution failed’ }); res.status(200).json({ result: stdout }); }); }

System Alert • ID: 9958
Target: Next.js API
Potential Vulnerability

Your Next.js API might be exposed to Command Injection

74% of Next.js apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.