Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Snyk CLI execution
✓ import { exec } from 'child_process'; exec('snyk test --json', (err, stdout) => { /* handle output */ });
The `snyk` npm package primarily provides the Snyk CLI executable. Direct JavaScript/TypeScript module imports for core scanning functionality are not part of its public API. Programmatic interaction is typically achieved by invoking the CLI as a child process, or by using dedicated Snyk SDKs like `@snyk/snyk-cli-wrapper` for more structured integration.
Snyk API (via HTTP client)
✓ import axios from 'axios'; axios.post('https://api.snyk.io/rest/orgs/{orgId}/test', { /* ... */ }, { headers: { 'Authorization': `token ${process.env.SNYK_TOKEN}` } });
For direct interaction with Snyk's services programmatically, it's recommended to use the official Snyk API (REST) via an HTTP client, rather than attempting to import internal modules from the `snyk` CLI package.
SnykCliArgs (Type Definition)
✓ import type { SnykCliArgs } from 'snyk/dist/cli/commands/types';
While functional imports are not typically exposed, the package does ship TypeScript type definitions for internal CLI structures, which can be useful for developers building wrappers or understanding CLI arguments. This is an internal path and may change without notice.
This quickstart demonstrates how to programmatically invoke the Snyk CLI using `child_process.exec` to scan a dynamically created `package.json` for known vulnerabilities. It includes error handling, JSON output parsing, and basic vulnerability reporting, requiring a configured Snyk token and global CLI installation.
import { exec } from 'child_process';
import path from 'path';
import { readFileSync, writeFileSync, mkdirSync } from 'fs';
// Create a dummy package.json for demonstration purposes
const projectPath = path.join(process.cwd(), 'snyk-quickstart-project');
mkdirSync(projectPath, { recursive: true });
writeFileSync(path.join(projectPath, 'package.json'), JSON.stringify({
name: 'my-vulnerable-app',
version: '1.0.0',
dependencies: {
'lodash': '4.17.15', // A version known to have vulnerabilities
'express': '4.17.1' // A common dependency
}
}, null, 2));
console.log('Running Snyk CLI test on a dummy project...');
// Important: Ensure SNYK_TOKEN is set as an environment variable (e.g., in .env or CI/CD secrets).
// Use `npx snyk auth` to authenticate your machine with Snyk.
const snykCommand = `npx snyk test --json --file=${path.join(projectPath, 'package.json')}`;
exec(snykCommand, { cwd: projectPath, env: { ...process.env, SNYK_TOKEN: process.env.SNYK_TOKEN ?? '' } }, (error, stdout, stderr) => {
if (error) {
// Snyk CLI often exits with a non-zero code (e.g., 1 or 2) even if it successfully finds vulnerabilities,
// but 2 indicates a failure (e.g. CLI couldn't run).
// We should still try to parse stdout if code is 1.
console.error(`Snyk CLI exited with code ${error.code}. Message: ${error.message}`);
if (stderr) console.error('Stderr:', stderr);
if (error.code === 2) return; // True failure, no output to parse.
}
if (stdout) {
try {
const results = JSON.parse(stdout);
if (results.vulnerabilities && results.vulnerabilities.length > 0) {
console.log(`Snyk scan completed. Found ${results.vulnerabilities.length} vulnerabilities.`);
results.vulnerabilities.slice(0, 3).forEach((vuln: any) => {
console.log(`- [${vuln.severity.toUpperCase()}] ${vuln.title} (Package: ${vuln.packageName}@${vuln.version})`);
console.log(` Fix advice: ${vuln.fixedIn ? 'Upgrade to ' + vuln.fixedIn : 'No direct fix available.'}`);
});
} else {
console.log('Snyk scan completed. No vulnerabilities found.');
}
} catch (parseError) {
console.error('Failed to parse Snyk JSON output. Stdout:', stdout);
if (error) console.error('Original CLI Error:', error);
}
} else if (stderr) {
console.error('Snyk CLI outputted only to stderr (likely an error):', stderr);
} else {
console.log('Snyk CLI ran, but produced no direct output to stdout or stderr.');
}
});
snyk --version
Debug
Known issues
breakingSnyk CLI versions prior to 1.1191.0 had an issue where authentication in certain environments (e.g., containers/pipelines) might fail due to incorrect reliance on a `TOKEN` environment variable.fixUpgrade the Snyk CLI to version 1.1191.0 or higher.
affects: <1.1191.0
breakingThe Snyk CLI is closed to external contributions as of July 22, 2024. While the project remains open-source for transparency, direct pull requests are no longer accepted.fixDevelopers should use the CLI as a consumer and report issues via official Snyk support channels. Focus on integrating the CLI into workflows rather than modifying its source.
affects: >=1.1200.0 (estimated)
breakingOlder versions of the `snyk` package (before 1.1064.0) were vulnerable to Command Injection (CVE-2022-22984). An incomplete fix for CVE-2022-40764 allowed attackers to run arbitrary commands by crafting command line flags, potentially in CI/CD pipelines.fixImmediately upgrade the Snyk CLI to version 1.1064.0 or higher. Ensure Docker images are updated to those released after 2022-11-29.
affects: <1.1064.0
gotchaThe Snyk CLI may automatically execute code (e.g., invoke package managers like npm, Gradle, Maven) as part of examining a codebase for vulnerabilities. Running `snyk test` on untrusted code with malicious configurations can expose your system to malicious code execution and exploits.fixAlways ensure you understand and trust the code in the directory you intend to scan with Snyk CLI. When in doubt, do not proceed with a scan.
affects: >=1.0.0
gotchaFor Snyk Open Source scanning, you must have the relevant package manager (e.g., npm, yarn, pip, Gradle, Maven) installed and available in your system's PATH. Snyk CLI cannot resolve dependencies without these third-party tools.fixInstall the appropriate package manager(s) for your project and ensure their executables are discoverable in your system's PATH environment variable. For Python projects, specify the Python command using `--python-command`.
affects: >=1.0.0
gotchaBefore testing an Open Source project for vulnerabilities, with limited exceptions, you must first build your project (e.g., `npm install`, `mvn install`). This ensures the dependency tree is fully resolved for Snyk to scan.fixAlways run your project's build command to install all dependencies before executing `snyk test` on an Open Source project.
affects: >=1.0.0
gotchaThe Snyk CLI's behavior can be influenced by different deployment channels, which users can select for varying stability levels. This could lead to inconsistencies or unexpected behavior if not managed properly.fixRefer to the Snyk documentation on 'Releases and channels for the Snyk CLI' to understand the stability level and expected behavior for your chosen channel. Be explicit about the channel in CI/CD if consistency is critical.
affects: >=1.1303.2
Errors
Common errors & fixes
snyk: command not found
The Snyk CLI is not installed globally or is not in the system's PATH, or `npx` is not available.
fixInstall Snyk globally using `npm install -g snyk` or `yarn global add snyk`. Alternatively, run Snyk commands using `npx snyk <command>`.
Authentication failed. Please check the API token on https://snyk.io
The Snyk API token is missing, invalid, or expired, or the user is not a member of a Snyk organization.
fixAuthenticate your machine with `snyk auth` and provide your Snyk API token. Ensure the token is valid and belongs to a user who is a member of an organization in Snyk.io. For CI/CD, ensure `SNYK_TOKEN` environment variable is correctly set.
Failed to get vulns
This generic error can indicate several issues, including authentication problems, a project being too large for scanning, or internal CLI errors.
fixFirst, verify authentication with `snyk auth`. If persistent, try scanning a smaller, simpler project. Consider adding `--debug` (`-d`) flag for more detailed logs. For very large projects, 'pruning' the dependency tree might help.
No supported projects detected
Snyk CLI could not find any recognizable manifest files (e.g., `package.json`, `pom.xml`, `Dockerfile`) in the current directory or specified path, or the project was not built (dependencies not installed).
fixEnsure you are running Snyk in a directory containing supported project files. For Open Source projects, run your package manager's install command (`npm install`, `yarn install`, `mvn install`) beforehand. Use `--file=<FILE_PATH>` to specify a manifest, or `--all-projects` for monorepos.
JSON output was incorrectly printed to stdout when only --json-file-output was specified
A bug in older Snyk CLI versions caused JSON output to be incorrectly printed to stdout even when directed to a file.
fixUpgrade Snyk CLI to version 1.1303.1 or later, which includes a fix for this bug.
Audit
Dependencies
noderequiredRequired runtime environment, specified as '>=12' in package.json. CLI functions are executed within Node.js.
various package managers (e.g., npm, yarn, Gradle, Maven)requiredRequired for Snyk Open Source scanning to resolve project dependencies. These tools must be installed and available in the system's PATH.
docker (for Snyk Container)optionalRequired for scanning container images. This is an optional dependency for users who utilize Snyk Container features.