Snyk CLI

1.1304.0 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.');
  }
});

view raw JSON →