Configuration options for initializing and customizing the GitLab API client behavior.
// Basic setup
const api = new Gitlab({
token: process.env.GITLAB_TOKEN
});
// Full configuration
const api = new Gitlab({
host: 'https://gitlab.com',
token: process.env.GITLAB_TOKEN,
camelize: true,
queryTimeout: 60000,
rateLimitDuration: 60,
sudo: 'username'
});Most common method - Use for user-based authentication
const api = new Gitlab({
host: 'https://gitlab.com',
token: 'glpat-xxxxxxxxxxxxxxxxxxxx'
});
// Required token scopes: api, read_api, read_user, read_repository, write_repositoryUse for OAuth applications
const api = new Gitlab({
host: 'https://gitlab.com',
oauthToken: 'oauth-token-here'
});Use in GitLab CI/CD pipelines
const api = new Gitlab({
host: process.env.CI_SERVER_URL,
jobToken: process.env.CI_JOB_TOKEN
});
// Available in all GitLab CI/CD jobs
// Limited to project-level accessUse when token needs to be fetched from secure storage
const api = new Gitlab({
host: 'https://gitlab.com',
token: async () => {
// Fetch token from secure storage, vault, etc.
const token = await fetchTokenFromVault();
return token;
}
});
// Token function is called for each request
// Useful for token rotation or vault integrationInitialize the GitLab API client with authentication and configuration options.
/**
* Main GitLab API client class
* @template C - When true, camelizes response keys (snake_case to camelCase)
*/
class Gitlab<C extends boolean = false> {
constructor(options: GitlabOptions<C>);
// All resource classes are available as properties
Projects: Projects<C>;
Issues: Issues<C>;
MergeRequests: MergeRequests<C>;
Users: Users<C>;
Groups: Groups<C>;
Pipelines: Pipelines<C>;
Jobs: Jobs<C>;
// ... 195+ additional resource classes
}/**
* Configuration options for Gitlab client
*/
type GitlabOptions<C extends boolean = false> = {
// Host configuration
/** GitLab instance URL. Default: 'https://gitlab.com' */
host?: string;
/** Additional URL prefix after /api/v4 */
prefixUrl?: string;
// Authentication (at least one required for most operations)
/** Personal or project access token */
token?: string | (() => Promise<string>);
/** OAuth 2.0 token */
oauthToken?: string | (() => Promise<string>);
/** CI/CD job token */
jobToken?: string | (() => Promise<string>);
// Response behavior
/** Convert response keys from snake_case to camelCase */
camelize?: C;
/** Request timeout in milliseconds. Default: 300000 (5 minutes) */
queryTimeout?: number | null;
// Impersonation
/** Perform API calls as different user (requires admin privileges) */
sudo?: string | number;
// Rate limiting
/** Custom rate limit configuration per endpoint */
rateLimits?: RateLimitOptions;
/** Rate limit timeout duration in seconds. Default: 60 */
rateLimitDuration?: number;
// Performance profiling
/** Enable GitLab performance profiling */
profileToken?: string;
/** Profiling mode. Default: 'execution' */
profileMode?: 'execution' | 'memory';
// HTTP configuration (Node.js only)
/** Custom HTTP agent for Node.js */
agent?: Agent;
};/**
* Rate limit configuration per endpoint using glob patterns
*/
type RateLimitOptions = Record<
string,
| number
| {
method: 'get' | 'post' | 'put' | 'patch' | 'delete';
limit: number;
}
>;Default Rate Limits (requests per minute):
**): 3000projects/import, projects/*/export, etc.): 6projects/*/issues/*/notes, etc.): 300projects/*/repository/archive*): 5projects/*/jobs): 600projects/*/members, groups/*/members): 60Individual resource classes can be instantiated separately.
/**
* Instantiate individual resource class
*/
class Projects<C extends boolean = false> {
constructor(options: BaseResourceOptions<C>);
}
type BaseResourceOptions<C extends boolean = false> = GitlabOptions<C> & {
/** Custom requester function */
requesterFn?: RequesterFn;
};Personal Access Token:
import { Gitlab } from '@gitbeaker/rest';
const api = new Gitlab({
host: 'https://gitlab.com',
token: 'glpat-xxxxxxxxxxxxxxxxxxxx'
});OAuth Token:
const api = new Gitlab({
host: 'https://gitlab.com',
oauthToken: 'oauth-token-here'
});Job Token (CI/CD):
const api = new Gitlab({
host: process.env.CI_SERVER_URL,
jobToken: process.env.CI_JOB_TOKEN
});Dynamic Token (async function):
const api = new Gitlab({
host: 'https://gitlab.com',
token: async () => {
// Fetch token from secure storage
return await getTokenFromVault();
}
});const api = new Gitlab({
host: 'https://gitlab.mycompany.com',
token: process.env.GITLAB_TOKEN
});// Enable camelCase conversion
const api = new Gitlab<true>({
token: process.env.GITLAB_TOKEN,
camelize: true
});
const project = await api.Projects.show(123);
console.log(project.defaultBranch); // camelCase
console.log(project.createdAt); // camelCaseconst api = new Gitlab({
token: process.env.GITLAB_TOKEN,
queryTimeout: 60000 // 1 minute timeout
});
// Disable timeout (use with caution)
const apiNoTimeout = new Gitlab({
token: process.env.GITLAB_TOKEN,
queryTimeout: null
});const api = new Gitlab({
token: process.env.GITLAB_TOKEN,
rateLimits: {
// Override default rate limit
'**': 1000,
// Specific endpoint rate limit
'projects/*/issues': 100,
// Method-specific rate limit
'projects/*/merge_requests': {
method: 'post',
limit: 50
}
},
rateLimitDuration: 30 // Wait 30 seconds when rate limit is hit
});Global Sudo:
// All requests will be made as 'username'
const api = new Gitlab({
token: 'admin-token',
sudo: 'username'
});
// Or by user ID
const api = new Gitlab({
token: 'admin-token',
sudo: 123
});Per-Request Sudo:
const api = new Gitlab({
token: 'admin-token'
});
// Single request as different user
await api.Issues.create(projectId, 'Title', {
sudo: 'username',
description: 'Created as username'
});
// By user ID
await api.Issues.create(projectId, 'Title', {
sudo: 123,
description: 'Created as user 123'
});const api = new Gitlab({
token: process.env.GITLAB_TOKEN,
profileToken: 'profile-token',
profileMode: 'execution' // or 'memory'
});
// Check response headers for profiling data
const project = await api.Projects.show(123, {
showExpanded: true
});
console.log(project.headers['x-runtime']); // Request duration// Works in browsers with native fetch
import { Gitlab } from 'https://esm.sh/@gitbeaker/rest';
const api = new Gitlab({
token: 'glpat-xxxxxxxxxxxxxxxxxxxx'
});
const projects = await api.Projects.all();import { Projects, Issues } from '@gitbeaker/rest';
// Instantiate only what you need (better tree-shaking)
const projects = new Projects({
host: 'https://gitlab.com',
token: process.env.GITLAB_TOKEN
});
const issues = new Issues({
host: 'https://gitlab.com',
token: process.env.GITLAB_TOKEN
});
const allProjects = await projects.all();
const allIssues = await issues.all({ projectId: 123 });// Development
const devConfig = {
host: 'https://gitlab-dev.mycompany.com',
token: process.env.GITLAB_DEV_TOKEN,
queryTimeout: 60000
};
// Production
const prodConfig = {
host: 'https://gitlab.mycompany.com',
token: process.env.GITLAB_PROD_TOKEN,
queryTimeout: 30000,
rateLimits: {
'**': 2000 // More conservative in prod
}
};
const config = process.env.NODE_ENV === 'production' ? prodConfig : devConfig;
const api = new Gitlab(config);import https from 'https';
const api = new Gitlab({
host: 'https://gitlab-dev.mycompany.com',
token: process.env.GITLAB_TOKEN,
agent: new https.Agent({
rejectUnauthorized: false // WARNING: Only for development/testing
})
});import https from 'https';
import { HttpsProxyAgent } from 'https-proxy-agent';
const proxyAgent = new HttpsProxyAgent('http://proxy.company.com:8080');
const api = new Gitlab({
host: 'https://gitlab.com',
token: process.env.GITLAB_TOKEN,
agent: proxyAgent
});const clients = {
primary: new Gitlab({
host: 'https://gitlab.com',
token: process.env.GITLAB_PRIMARY_TOKEN
}),
secondary: new Gitlab({
host: 'https://gitlab-secondary.com',
token: process.env.GITLAB_SECONDARY_TOKEN
})
};
// Use appropriate client
const projects = await clients.primary.Projects.all();// Mock client for testing
const mockApi = new Gitlab({
host: 'https://gitlab-test.local',
token: 'test-token',
queryTimeout: 1000 // Short timeout for tests
});
// Or use individual resource classes with custom requester
import { Projects } from '@gitbeaker/rest';
const projects = new Projects({
token: 'test-token',
requesterFn: mockRequesterFunction // Your mock
});// .gitlab-ci.yml context
const api = new Gitlab({
host: process.env.CI_SERVER_URL,
jobToken: process.env.CI_JOB_TOKEN
});
// Works within the CI pipeline's project context
const currentProject = await api.Projects.show(process.env.CI_PROJECT_ID);// Verify token works
try {
const currentUser = await api.Users.showCurrentUser();
console.log('Authenticated as:', currentUser.username);
} catch (error) {
console.error('Token authentication failed');
console.error('Check: 1) Token is valid, 2) Token has required scopes, 3) Token not expired');
}// Increase timeout for slow connections
const api = new Gitlab({
token: process.env.GITLAB_TOKEN,
queryTimeout: 120000 // 2 minutes
});// Check current rate limit status from response headers
const project = await api.Projects.show(123, {
showExpanded: true
});
console.log('Rate limit:', project.headers['ratelimit-limit']);
console.log('Remaining:', project.headers['ratelimit-remaining']);
console.log('Reset:', project.headers['ratelimit-reset']);