npm Registry API Client
    Preparing search index...

    Class NpmClient

    Main entry point for the npm Registry API client.

    import { NpmClient } from 'npmjs-api-client';

    const npm = new NpmClient();

    // Get full package metadata
    const pkg = await npm.package('react');

    // Get a specific version
    const v18 = await npm.package('react').version('18.2.0');

    // Get the latest version
    const latest = await npm.package('react').latest();

    // Get dist-tags
    const tags = await npm.package('react').distTags();

    // Search packages
    const results = await npm.search({ text: 'react hooks', size: 10 });

    // Get download stats
    const stats = await npm.package('react').downloads('last-week');

    // Get all packages by a maintainer
    const result = await npm.maintainer('sindresorhus').packages();
    Index

    Constructors

    Methods

    • Runs a full security audit against the npm registry.

      The payload mirrors the top-level structure of package-lock.json: a name, version, and a dependencies map of resolved packages with their versions, integrity hashes, and nested sub-dependencies.

      Returns detailed advisory objects for every vulnerability found, along with recommended actions (update, install, or manual review).

      POST /-/npm/v1/security/audits

      Parameters

      • payload: NpmAuditPayload

        Lock-file-shaped dependency tree to audit

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmAuditResult>

      Full audit report with advisories, actions, and vulnerability counts

      const result = await npm.audit({
      name: 'my-app',
      version: '1.0.0',
      requires: { lodash: '^4.17.11' },
      dependencies: {
      lodash: { version: '4.17.11', integrity: 'sha512-...' },
      },
      });

      console.log(result.metadata.vulnerabilities);
      // { info: 0, low: 0, moderate: 1, high: 0, critical: 0 }

      Object.values(result.advisories).forEach(a => {
      console.log(`[${a.severity}] ${a.title} — ${a.module_name}@${a.vulnerable_versions}`);
      console.log(` Fix: upgrade to ${a.patched_versions}`);
      });
    • Runs a quick security audit against the npm registry.

      Same payload as audit but returns only vulnerability counts by severity — no advisory details or recommended actions. Faster and lighter than the full audit.

      POST /-/npm/v1/security/audits/quick

      Parameters

      • payload: NpmAuditPayload

        Lock-file-shaped dependency tree to audit

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmAuditQuickResult>

      Vulnerability counts by severity and dependency totals

      const result = await npm.auditQuick({
      name: 'my-app',
      version: '1.0.0',
      requires: { lodash: '^4.17.11' },
      dependencies: {
      lodash: { version: '4.17.11', integrity: 'sha512-...' },
      },
      });

      const { high, critical } = result.metadata.vulnerabilities;
      if (high + critical > 0) {
      console.error(`Found ${high} high and ${critical} critical vulnerabilities`);
      }
    • Fetches the total download count for multiple packages.

      GET /downloads/point/{period}/{name1},{name2},... (via api.npmjs.org)

      npm's bulk lookup accepts at most 128 unscoped packages, so unscoped names are sent in batches of 128, and each scoped package (@scope/name) is fetched with its own request.

      Parameters

      • packages: string[]

        Package names to fetch downloads for; duplicates are ignored

      • period: NpmDownloadPeriod = 'last-month'

        Named period or date range (default: 'last-month')

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the requests

      Returns Promise<NpmBulkDownloads>

      A map of package name to download point data, or null for packages that do not exist

      const stats = await npm.bulkDownloads(['react', 'vue', '@angular/core']);
      console.log(stats['react']?.downloads); // 18591460
      console.log(stats['@angular/core']?.downloads); // 1800000
    • Fetches the per-day download breakdown for a package over a given period.

      GET /downloads/range/{period}/{package} (via api.npmjs.org)

      Convenience method — equivalent to npm.package(name).downloadRange(period).

      Parameters

      • period: NpmDownloadPeriod

        Named period or date range

      • packageName: string

        The package name

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmDownloadRange>

      Download range data with a per-day array

      const range = await npm.downloadRange('last-month', 'react');
      range.downloads.forEach(d => console.log(d.day, d.downloads));
    • Fetches the total download count for a package over a given period.

      GET /downloads/point/{period}/{package} (via api.npmjs.org)

      Convenience method — equivalent to npm.package(name).downloads(period).

      Parameters

      • period: NpmDownloadPeriod

        Named period or date range

      • packageName: string

        The package name

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmDownloadPoint>

      Download point data including total count and date range

      const stats = await npm.downloads('last-week', 'react');
      console.log(stats.downloads);
    • Returns a MaintainerResource for a given npm username, providing access to all packages they maintain.

      GET /-/v1/search?text=maintainer:{username}

      Parameters

      • username: string

        The npm username (e.g. 'sindresorhus', 'pilmee')

      Returns MaintainerResource

      A maintainer resource with a packages() method

      const result = await npm.maintainer('sindresorhus').packages();
      console.log(`${result.total} packages`);
      result.objects.forEach(o => console.log(o.package.name, o.package.version));

      // Paginate
      const page2 = await npm.maintainer('sindresorhus').packages({ size: 25, from: 25 });
    • Unsubscribes a callback previously registered with NpmClient.on. If the callback was registered more than once, only the most recent registration is removed. Unknown callbacks are ignored.

      Removing a listener while an event is being emitted does not affect that emission; the change applies from the next request.

      Type Parameters

      • K extends "request"

      Parameters

      Returns this

      const log = (event: RequestEvent) => console.log(event.url);
      npm.on('request', log);
      // ...
      npm.off('request', log);
    • Subscribes to a client event. Listener exceptions and rejected promises are isolated from requests. Async listeners are not awaited; callbacks handle their own error reporting.

      Type Parameters

      • K extends "request"

      Parameters

      Returns this

      npm.on('request', (event) => {
      console.log(`${event.method} ${event.url} — ${event.durationMs}ms`);
      if (event.error) console.error('Request failed:', event.error);
      });
    • Returns an OrgResource for a given npm organization, providing authenticated access to org packages, teams, and members.

      These endpoints require a registry auth token with org access.

      Parameters

      • org: string

        The npm org name, with or without the leading @

      Returns OrgResource

      An org resource with packages(), teams(), members(), and teamMembers() methods

      const npm = new NpmClient({ token: 'npm_...' });
      const packages = await npm.org('npmcli').packages();
      const teams = await npm.org('npmcli').teams();
    • Returns a PackageResource for a given package name, providing access to package metadata, versions, dist-tags, and download statistics.

      The returned resource can be awaited directly to fetch the full packument, or chained to access nested resources.

      Parameters

      • name: string

        The package name (e.g. 'react', '@types/node')

      Returns PackageResource

      A chainable package resource

      const pkg  = await npm.package('react');
      const v18 = await npm.package('react').version('18.2.0');
      const tags = await npm.package('react').distTags();
    • Searches for packages on the npm registry.

      GET /-/v1/search

      Parameters

      • params: NpmSearchParams

        Search parameters (required: text)

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmSearchResult>

      Search results including packages, scores, and total count

      const results = await npm.search({ text: 'react state management', size: 5 });
      results.objects.forEach(o => console.log(o.package.name, o.package.version));
    • Returns top packages for a keyword.

      GET /-/v1/search?text=keywords:{keyword}&size={n}

      Parameters

      • keyword: string

        Keyword to filter by

      • n: number = 20

        Number of packages to return (default: 20, max: 250)

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmSearchResult>

      Search results including packages, scores, and total count

    • Returns top packages ranked by maintenance.

      Parameters

      • n: number = 20

        Number of packages to return (default: 20, max: 250)

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmSearchResult>

      Search results including packages, scores, and total count

      npm's search API ignores ranking weights, so this returns the same results as NpmClient.topPackages. To rank by popularity, sort search results by their downloads field.

      GET /-/v1/search?text=keywords:javascript&size={n}&maintenance=1&quality=0&popularity=0

    • Returns top packages ranked by popularity.

      Parameters

      • n: number = 20

        Number of packages to return (default: 20, max: 250)

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmSearchResult>

      Search results including packages, scores, and total count

      npm's search API ignores ranking weights, so this returns the same results as NpmClient.topPackages. To rank by popularity, sort search results by their downloads field.

      GET /-/v1/search?text=keywords:javascript&size={n}&popularity=1&quality=0&maintenance=0

    • Returns top packages ranked by quality.

      Parameters

      • n: number = 20

        Number of packages to return (default: 20, max: 250)

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmSearchResult>

      Search results including packages, scores, and total count

      npm's search API ignores ranking weights, so this returns the same results as NpmClient.topPackages. To rank by popularity, sort search results by their downloads field.

      GET /-/v1/search?text=keywords:javascript&size={n}&quality=1&popularity=0&maintenance=0

    • Returns top packages for a scope.

      GET /-/v1/search?text=scope:{scope}&size={n}

      Parameters

      • scope: string

        Scope to filter by, with or without the leading @

      • n: number = 20

        Number of packages to return (default: 20, max: 250)

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmSearchResult>

      Search results including packages, scores, and total count

    • Returns the top packages according to npm search's default ranking.

      GET /-/v1/search?text=keywords:javascript&size={n}

      npm ranks results by search relevance. npm requires a non-empty text query, so this helper uses a broad JavaScript keyword search.

      Parameters

      • n: number = 20

        Number of packages to return (default: 20, max: 250)

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmSearchResult>

      Search results including packages, scores, and total count

      const top = await npm.topPackages(10);
      top.objects.forEach(o => console.log(o.package.name, o.downloads?.weekly));
    • Returns a UserResource for a given npm username, providing authenticated access to the registry user profile and user package list.

      These endpoints require a registry auth token.

      Parameters

      • username: string

        The npm username (e.g. 'pilmee')

      Returns UserResource

      A user resource with get() and packages() methods

      const npm = new NpmClient({ token: 'npm_...' });
      const user = await npm.user('pilmee').get();
      const packages = await npm.user('pilmee').packages();
    • Returns the npm username associated with the configured auth token.

      Useful for validating a token and discovering which account it belongs to without knowing the username in advance.

      GET /-/whoami

      Requires a registry auth token — throws NpmApiError with status 401 if no token is set or the token is invalid.

      Parameters

      • Optionalsignal: AbortSignal

        Optional AbortSignal to cancel the request

      Returns Promise<NpmWhoami>

      The username associated with the token

      const npm = new NpmClient({ token: 'npm_...' });
      const { username } = await npm.whoami();
      console.log(username); // 'pilmee'