Bitbucket.js API Client
bitbucket (Bitbucket.js) is a comprehensive JavaScript API client for interacting with the Bitbucket Cloud API, designed for both Node.js and browser environments. The current stable version is 2.12.0. This library aims to provide a robust and type-safe interface, shipping with TypeScript definitions, making it well-suited for modern JavaScript and TypeScript projects. It supports various authentication methods, including username/password and token-based authentication, and provides access to numerous Bitbucket API namespaces such as repositories, pull requests, pipelines, and users. The project draws heavy inspiration from `octokit/rest.js`, suggesting a similar, well-structured, and idiomatic approach to API interactions. While no explicit release cadence is stated, it appears to be actively maintained, with regular updates to reflect the latest Bitbucket API changes and bug fixes. Its key differentiators include its dual Node.js/browser support, extensive API coverage, and strong typing, simplifying complex API interactions.
Common errors
-
ReferenceError: Bitbucket is not defined
cause Incorrectly importing or referencing the Bitbucket class, often when mixing CommonJS `require` syntax with an ESM-only context, or when using the UMD build without global access.fixFor Node.js ESM projects, use `import { Bitbucket } from 'bitbucket'`. For CommonJS Node.js, use `const { Bitbucket } = require('bitbucket')`. In a browser with the UMD build, ensure the `Bitbucket` global is available after script loading. -
TypeError: bitbucket.repositories.listGlobal is not a function
cause Attempting to call an API method with incorrect arguments or on a non-existent namespace/method. This can also happen if the API client instance is not correctly initialized.fixVerify the method name and namespace against the official documentation (e.g., `bitbucketjs.netlify.app`). Ensure all required parameters are passed as an object to the API method. -
Error: Request failed with status code 400
cause A `400 Bad Request` status indicates that the API request itself was malformed, missing required parameters, or contained invalid data.fixReview the `err.error` object in the catch block for specific details from the Bitbucket API about what caused the bad request. Ensure all required parameters for the specific API method are correctly formatted and provided.
Warnings
- breaking Major version updates, particularly from v1 to v2, often introduce breaking changes in API method signatures, response structures, or authentication mechanisms. Always review the official changelog or migration guide when upgrading across major versions to avoid unexpected issues. Specific changes may include renaming methods, altering parameter requirements, or updating the base URL.
- gotcha Bitbucket API enforces rate limits on requests. Exceeding these limits will result in `429 Too Many Requests` errors. The client library does not inherently handle retry logic or backoff strategies out-of-the-box, which must be implemented by the consumer.
- gotcha Authentication failures often manifest as `401 Unauthorized` or `403 Forbidden` errors. This can be due to incorrect tokens, expired credentials, or insufficient permissions granted to the authenticated user or token.
- gotcha When using the client in a browser environment, be mindful of cross-origin resource sharing (CORS) policies. Direct API calls from a browser to Bitbucket's API might be blocked if the response does not include appropriate CORS headers, especially for non-simple requests.
Install
-
npm install bitbucket -
yarn add bitbucket -
pnpm add bitbucket
Imports
- Bitbucket
const { Bitbucket } = require('bitbucket')import { Bitbucket } from 'bitbucket' - Bitbucket
import { Bitbucket } from 'bitbucket'const { Bitbucket } = require('bitbucket') - ClientOptions
import type { ClientOptions } from 'bitbucket'import { ClientOptions } from 'bitbucket'
Quickstart
import { Bitbucket } from 'bitbucket';
const BITBUCKET_ACCESS_TOKEN = process.env.BITBUCKET_ACCESS_TOKEN ?? '';
if (!BITBUCKET_ACCESS_TOKEN) {
console.error('Error: BITBUCKET_ACCESS_TOKEN environment variable is not set.');
process.exit(1);
}
const clientOptions = {
baseUrl: 'https://api.bitbucket.org/2.0',
auth: {
token: BITBUCKET_ACCESS_TOKEN,
},
request: {
timeout: 10000, // 10 seconds
},
};
const bitbucket = new Bitbucket(clientOptions);
async function listMyRepositories() {
try {
console.log('Fetching repositories...');
const { data } = await bitbucket.repositories.listForUser({ username: 'me' });
if (data && data.values) {
console.log('Found the following repositories:');
data.values.forEach(repo => console.log(`- ${repo.name} (${repo.full_name})`));
} else {
console.log('No repositories found or unexpected response format.');
}
} catch (err) {
if (err.status === 401 || err.status === 403) {
console.error('Authentication failed. Check your BITBUCKET_ACCESS_TOKEN and permissions.');
} else {
console.error(`Error listing repositories: ${err.message}`);
if (err.error) {
console.error('API Error details:', err.error);
}
}
}
}
listMyRepositories();