When AI generated code add external libraries to your project, you are assuming they come from reliable sources. If you're not careful, you might accidentally pull a malicious or incorrect package.

From Helpful to Harmful: How AI Recommendations Destroyed My OS

This is called "package hallucination" .

Attackers often publish fake packages with names similar to popular ones (typesquatting), hoping developers will install them by mistake.

These packages can inject harmful code into your system through the package supply chain.

In a recent paper, the authors found a lot of evidence of these attacks on the wild. Researchers tested 16 language models and generated more than half a million code snippets. They found that nearly 440,000 dependencies pointed to libraries that simply don't exist.

These are very harmful backdoors for hackers.

Package hallucination happens when you assume a package exists (based on naming patterns or habits), but:

  • It doesn’t exist at all
  • It’s a fake or typosquatted version
  • It’s abandoned or totally unrelated

To avoid it:

  1. Check npm before installing Visit npmjs.com and search the package. Look at downloads, maintainers, and repo links.

  2. Verify the GitHub repo Make sure there’s actual code, documentation, and activity.

  3. Prefer official scoped packages For example, use @nestjs/swagger instead of a similarly named unscoped version.

  4. Be cautious with similar names lodashs, react-routerr, or vue-clii are classic typosquatting tricks.

  5. Use tools like Socket These can warn you about risky or suspicious packages.

An example of what you shouldn't do:

// package.json
{
  "name": "my-app",
  "dependencies": {
    "react": "^18.2.0",
    "lodahs": "1.0.0",  // Typosquatting attack
    "internal-logger": "2.1.0" 
    // Vulnerable to dependency confusion
  }
}

Do this instead:

// package.json
{
  "name": "my-app",
  "dependencies": {
    "react": "18.2.0",
    "lodash": "4.17.21",  // Correct spelling with exact version
    "@company-scope/internal-logger": "2.1.0" // Scoped package
  },
  "resolutions": {
    "lodash": "4.17.21"  
    // Force specific version for nested dependencies
  },
  "packageManager": "yarn@3.2.0" // Lock package manager version
}

npm has millions of packages—some real, some fake. Just because something installs doesn’t mean it’s safe or useful.

Always double-check. Don’t trust your assumptions.