{"id":14921,"library":"snyk","title":"Snyk CLI","description":"The `snyk` npm package provides the Snyk Command Line Interface (CLI), a developer-first, cloud-native security tool designed to integrate vulnerability scanning and monitoring into the software development workflow. It identifies and helps fix security issues across various content types, including open-source dependencies (Snyk Open Source), proprietary application code (Snyk Code), container images (Snyk Container), and Infrastructure as Code (Snyk IaC). The CLI is currently at version 1.1304.0 and is updated very frequently, often with multiple releases per month, sometimes weekly, to deliver new features, bug fixes, and security enhancements. Its key differentiators include broad scanning capabilities for diverse project types, seamless integration into local development environments and CI/CD pipelines, and comprehensive reporting with actionable fix guidance. While the package itself contains internal library components, its primary public interface and intended use are via the command line.","status":"active","version":"1.1304.0","language":"javascript","source_language":"en","source_url":"https://github.com/snyk/snyk","tags":["javascript","security","vulnerabilities","advisories","audit","snyk","scan","docker","container"],"install":[{"cmd":"npm install snyk","lang":"bash","label":"npm"},{"cmd":"yarn add snyk","lang":"bash","label":"yarn"},{"cmd":"pnpm add snyk","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required runtime environment, specified as '>=12' in package.json. CLI functions are executed within Node.js.","package":"node","optional":false},{"reason":"Required for Snyk Open Source scanning to resolve project dependencies. These tools must be installed and available in the system's PATH.","package":"various package managers (e.g., npm, yarn, Gradle, Maven)","optional":false},{"reason":"Required for scanning container images. This is an optional dependency for users who utilize Snyk Container features.","package":"docker (for Snyk Container)","optional":true}],"imports":[{"note":"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.","symbol":"Snyk CLI execution","correct":"import { exec } from 'child_process'; exec('snyk test --json', (err, stdout) => { /* handle output */ });"},{"note":"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.","symbol":"Snyk API (via HTTP client)","correct":"import axios from 'axios'; axios.post('https://api.snyk.io/rest/orgs/{orgId}/test', { /* ... */ }, { headers: { 'Authorization': `token ${process.env.SNYK_TOKEN}` } });"},{"note":"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.","symbol":"SnykCliArgs (Type Definition)","correct":"import type { SnykCliArgs } from 'snyk/dist/cli/commands/types';"}],"quickstart":{"code":"import { exec } from 'child_process';\nimport path from 'path';\nimport { readFileSync, writeFileSync, mkdirSync } from 'fs';\n\n// Create a dummy package.json for demonstration purposes\nconst projectPath = path.join(process.cwd(), 'snyk-quickstart-project');\nmkdirSync(projectPath, { recursive: true });\nwriteFileSync(path.join(projectPath, 'package.json'), JSON.stringify({\n  name: 'my-vulnerable-app',\n  version: '1.0.0',\n  dependencies: {\n    'lodash': '4.17.15', // A version known to have vulnerabilities\n    'express': '4.17.1' // A common dependency\n  }\n}, null, 2));\n\nconsole.log('Running Snyk CLI test on a dummy project...');\n\n// Important: Ensure SNYK_TOKEN is set as an environment variable (e.g., in .env or CI/CD secrets).\n// Use `npx snyk auth` to authenticate your machine with Snyk.\nconst snykCommand = `npx snyk test --json --file=${path.join(projectPath, 'package.json')}`;\n\nexec(snykCommand, { cwd: projectPath, env: { ...process.env, SNYK_TOKEN: process.env.SNYK_TOKEN ?? '' } }, (error, stdout, stderr) => {\n  if (error) {\n    // Snyk CLI often exits with a non-zero code (e.g., 1 or 2) even if it successfully finds vulnerabilities,\n    // but 2 indicates a failure (e.g. CLI couldn't run).\n    // We should still try to parse stdout if code is 1.\n    console.error(`Snyk CLI exited with code ${error.code}. Message: ${error.message}`);\n    if (stderr) console.error('Stderr:', stderr);\n    if (error.code === 2) return; // True failure, no output to parse.\n  }\n  \n  if (stdout) {\n    try {\n      const results = JSON.parse(stdout);\n      if (results.vulnerabilities && results.vulnerabilities.length > 0) {\n        console.log(`Snyk scan completed. Found ${results.vulnerabilities.length} vulnerabilities.`);\n        results.vulnerabilities.slice(0, 3).forEach((vuln: any) => {\n          console.log(`- [${vuln.severity.toUpperCase()}] ${vuln.title} (Package: ${vuln.packageName}@${vuln.version})`);\n          console.log(`  Fix advice: ${vuln.fixedIn ? 'Upgrade to ' + vuln.fixedIn : 'No direct fix available.'}`);\n        });\n      } else {\n        console.log('Snyk scan completed. No vulnerabilities found.');\n      }\n    } catch (parseError) {\n      console.error('Failed to parse Snyk JSON output. Stdout:', stdout); \n      if (error) console.error('Original CLI Error:', error);\n    }\n  } else if (stderr) {\n    console.error('Snyk CLI outputted only to stderr (likely an error):', stderr);\n  } else {\n    console.log('Snyk CLI ran, but produced no direct output to stdout or stderr.');\n  }\n});\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Upgrade the Snyk CLI to version 1.1191.0 or higher.","message":"Snyk 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.","severity":"breaking","affected_versions":"<1.1191.0"},{"fix":"Developers 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.","message":"The 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.","severity":"breaking","affected_versions":">=1.1200.0 (estimated)"},{"fix":"Immediately upgrade the Snyk CLI to version 1.1064.0 or higher. Ensure Docker images are updated to those released after 2022-11-29.","message":"Older 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.","severity":"breaking","affected_versions":"<1.1064.0"},{"fix":"Always 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.","message":"The 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Install 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`.","message":"For 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always run your project's build command to install all dependencies before executing `snyk test` on an Open Source project.","message":"Before 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer 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.","message":"The 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.","severity":"gotcha","affected_versions":">=1.1303.2"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Install Snyk globally using `npm install -g snyk` or `yarn global add snyk`. Alternatively, run Snyk commands using `npx snyk <command>`.","cause":"The Snyk CLI is not installed globally or is not in the system's PATH, or `npx` is not available.","error":"snyk: command not found"},{"fix":"Authenticate 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.","cause":"The Snyk API token is missing, invalid, or expired, or the user is not a member of a Snyk organization.","error":"Authentication failed. Please check the API token on https://snyk.io"},{"fix":"First, 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.","cause":"This generic error can indicate several issues, including authentication problems, a project being too large for scanning, or internal CLI errors.","error":"Failed to get vulns"},{"fix":"Ensure 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.","cause":"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).","error":"No supported projects detected"},{"fix":"Upgrade Snyk CLI to version 1.1303.1 or later, which includes a fix for this bug.","cause":"A bug in older Snyk CLI versions caused JSON output to be incorrectly printed to stdout even when directed to a file.","error":"JSON output was incorrectly printed to stdout when only --json-file-output was specified"}],"ecosystem":"npm"}