or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-octokit

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/octokit@5.0.x

To install, run

npx @tessl/cli install tessl/npm-octokit@5.0.0

0

# Octokit.js

1

2

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno. Octokit.js integrates three main Octokit libraries: API client for REST/GraphQL requests and authentication, App client for GitHub Apps with webhooks and OAuth support, and Action client for pre-authenticated single repository access.

3

4

## Package Information

5

6

- **Package Name**: octokit

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install octokit`

10

11

## Core Imports

12

13

```typescript

14

import { Octokit, App, OAuthApp, RequestError } from "octokit";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { Octokit, App, OAuthApp, RequestError } = require("octokit");

21

```

22

23

For pagination types:

24

25

```typescript

26

import type { PageInfoForward, PageInfoBackward } from "octokit";

27

```

28

29

## Basic Usage

30

31

```typescript

32

import { Octokit } from "octokit";

33

34

// Create an authenticated client

35

const octokit = new Octokit({

36

auth: "your-token-here",

37

});

38

39

// Make REST API requests

40

const { data: user } = await octokit.rest.users.getAuthenticated();

41

console.log(`Hello, ${user.login}!`);

42

43

// Use GraphQL

44

const { repository } = await octokit.graphql(`

45

query ($owner: String!, $name: String!) {

46

repository(owner: $owner, name: $name) {

47

stargazerCount

48

}

49

}

50

`, {

51

owner: "octokit",

52

name: "octokit.js"

53

});

54

55

// Paginate through REST API results

56

const issues = await octokit.paginate(octokit.rest.issues.listForRepo, {

57

owner: "octokit",

58

repo: "octokit.js"

59

});

60

61

// GraphQL pagination

62

const { allIssues } = await octokit.graphql.paginate(`

63

query allIssues($owner: String!, $repo: String!, $cursor: String) {

64

repository(owner: $owner, name: $repo) {

65

issues(first: 100, after: $cursor) {

66

nodes { title }

67

pageInfo { hasNextPage, endCursor }

68

}

69

}

70

}

71

`, { owner: "octokit", repo: "octokit.js" });

72

```

73

74

## Architecture

75

76

Octokit.js is built around a plugin architecture with these core components:

77

78

- **Core API Client**: Base GitHub API functionality with authentication and request handling

79

- **Plugin System**: Extensible architecture with built-in plugins for common use cases

80

- **REST Endpoint Methods**: Pre-configured methods for all GitHub REST API endpoints

81

- **GraphQL Support**: Query interface with pagination support for GitHub's GraphQL API

82

- **Retry & Throttling**: Automatic request retry and rate limiting handling

83

- **Multi-Platform**: Universal compatibility across browsers, Node.js, and Deno

84

85

## Capabilities

86

87

### Primary API Client

88

89

Core GitHub API client with REST, GraphQL, authentication, and built-in best practices including retry logic, rate limiting, and pagination.

90

91

```typescript { .api }

92

class Octokit {

93

constructor(options?: OctokitOptions);

94

95

// REST API methods (from plugin)

96

rest: RestEndpointMethods;

97

98

// Core request method

99

request<T = any>(route: string, options?: RequestOptions): Promise<OctokitResponse<T>>;

100

101

// GraphQL query method

102

graphql<T = any>(query: string, variables?: Record<string, any>): Promise<T>;

103

104

// GraphQL pagination method

105

graphql: {

106

paginate<T>(query: string, variables?: Record<string, any>): Promise<T>;

107

};

108

109

// Pagination for REST and GraphQL

110

paginate<T>(

111

method: Function,

112

parameters?: Record<string, any>

113

): Promise<T[]>;

114

115

// Pagination iterator for memory-efficient iteration

116

paginate: {

117

iterator<T>(

118

method: Function,

119

parameters?: Record<string, any>

120

): AsyncIterable<{ data: T[] }>;

121

};

122

123

// Authentication method

124

auth(): Promise<Authentication>;

125

126

// Logging interface

127

log: {

128

debug: (message: string, info?: object) => void;

129

info: (message: string, info?: object) => void;

130

warn: (message: string, info?: object) => void;

131

error: (message: string, info?: object) => void;

132

};

133

}

134

135

interface OctokitOptions {

136

auth?: string | AuthInterface | AuthOptions;

137

baseUrl?: string;

138

request?: RequestOptions;

139

userAgent?: string;

140

throttle?: {

141

onRateLimit?: (retryAfter: number, options: Required<EndpointDefaults>, octokit: Octokit) => boolean;

142

onSecondaryRateLimit?: (retryAfter: number, options: Required<EndpointDefaults>, octokit: Octokit) => boolean;

143

};

144

}

145

146

interface OctokitResponse<T> {

147

status: number;

148

url: string;

149

headers: ResponseHeaders;

150

data: T;

151

}

152

153

interface RequestOptions {

154

method?: string;

155

url?: string;

156

headers?: Record<string, string>;

157

body?: any;

158

request?: {

159

timeout?: number;

160

retries?: number;

161

retryDelay?: number;

162

};

163

}

164

165

type RestEndpointMethods = {

166

[scope: string]: {

167

[method: string]: (parameters?: any) => Promise<OctokitResponse<any>>;

168

};

169

};

170

```

171

172

**Usage Examples:**

173

174

```typescript

175

import { Octokit } from "octokit";

176

177

// Basic authentication

178

const octokit = new Octokit({

179

auth: process.env.GITHUB_TOKEN,

180

});

181

182

// Custom configuration

183

const octokit = new Octokit({

184

auth: "token",

185

baseUrl: "https://api.github.com",

186

userAgent: "my-app/1.0.0",

187

throttle: {

188

onRateLimit: (retryAfter, options, octokit) => {

189

octokit.log.warn(`Request quota exhausted for request ${options.method} ${options.url}`);

190

return true; // retry once

191

},

192

},

193

});

194

195

// Making requests

196

const repos = await octokit.rest.repos.listForAuthenticatedUser();

197

198

// Paginate all results

199

const issues = await octokit.paginate(octokit.rest.issues.listForRepo, {

200

owner: "owner",

201

repo: "repo"

202

});

203

204

// Memory-efficient pagination with iterator

205

for await (const { data: issues } of octokit.paginate.iterator(octokit.rest.issues.listForRepo, {

206

owner: "owner",

207

repo: "repo",

208

per_page: 100

209

})) {

210

for (const issue of issues) {

211

console.log(`Issue #${issue.number}: ${issue.title}`);

212

}

213

}

214

```

215

216

### GitHub App Client

217

218

Client for GitHub Apps with pre-configured Octokit integration, webhooks, and installation management.

219

220

```typescript { .api }

221

class App {

222

constructor(options: AppOptions);

223

224

// Pre-configured Octokit instance

225

octokit: Octokit;

226

227

// Get installation-specific Octokit client

228

getInstallationOctokit(installationId: number): Promise<Octokit>;

229

230

// Iterate through all repositories the app is installed on

231

eachRepository: {

232

iterator(): AsyncIterable<{ octokit: Octokit; repository: Repository }>;

233

};

234

235

// Webhook handling

236

webhooks: {

237

on: (event: string, handler: Function) => void;

238

onAny: (handler: Function) => void;

239

removeListener: (event: string, handler: Function) => void;

240

verify: (payload: string, signature: string) => boolean;

241

verifyAndReceive: (options: VerifyAndReceiveOptions) => Promise<void>;

242

};

243

244

// OAuth handling (if configured)

245

oauth?: {

246

on: (event: string, handler: Function) => void;

247

createToken: (options: any) => Promise<any>;

248

};

249

}

250

251

interface AppOptions {

252

appId: number;

253

privateKey: string;

254

installationId?: number;

255

clientId?: string;

256

clientSecret?: string;

257

webhooks?: {

258

secret?: string;

259

};

260

oauth?: {

261

clientId?: string;

262

clientSecret?: string;

263

};

264

Octokit?: typeof Octokit;

265

}

266

267

interface Repository {

268

id: number;

269

name: string;

270

full_name: string;

271

owner: {

272

login: string;

273

id: number;

274

};

275

private: boolean;

276

description?: string;

277

}

278

279

interface VerifyAndReceiveOptions {

280

id: string;

281

name: string;

282

signature: string;

283

payload: string;

284

}

285

```

286

287

**Usage Examples:**

288

289

```typescript

290

import { App } from "octokit";

291

292

// Create GitHub App

293

const app = new App({

294

appId: 123456,

295

privateKey: process.env.PRIVATE_KEY,

296

});

297

298

// Get installation client

299

const installationOctokit = await app.getInstallationOctokit(7654321);

300

const repos = await installationOctokit.rest.apps.listReposAccessibleToInstallation();

301

302

// Iterate through all repositories the app is installed on

303

for await (const { octokit, repository } of app.eachRepository.iterator()) {

304

console.log(`Processing repository: ${repository.full_name}`);

305

// Use octokit instance scoped to this repository

306

}

307

308

// Handle webhooks

309

app.webhooks.on("push", async ({ payload }) => {

310

console.log(`Received push event for ${payload.repository.full_name}`);

311

});

312

313

// Verify and receive webhooks in serverless environments

314

await app.webhooks.verifyAndReceive({

315

id: request.headers["x-github-delivery"],

316

name: request.headers["x-github-event"],

317

signature: request.headers["x-hub-signature-256"],

318

payload: request.body,

319

});

320

```

321

322

### OAuth App Client

323

324

Client for OAuth Apps with pre-configured Octokit integration and OAuth flow handling.

325

326

```typescript { .api }

327

class OAuthApp {

328

constructor(options: OAuthAppOptions);

329

330

// Pre-configured Octokit instance

331

octokit: Octokit;

332

333

// Create user access token

334

createToken(options: CreateTokenOptions): Promise<CreateTokenResult>;

335

336

// Check token

337

checkToken(options: CheckTokenOptions): Promise<CheckTokenResult>;

338

339

// Reset token

340

resetToken(options: ResetTokenOptions): Promise<ResetTokenResult>;

341

342

// Delete token

343

deleteToken(options: DeleteTokenOptions): Promise<void>;

344

345

// Get user Octokit client

346

getUserOctokit(options: GetUserOctokitOptions): Octokit;

347

}

348

349

interface OAuthAppOptions {

350

clientId: string;

351

clientSecret: string;

352

Octokit?: typeof Octokit;

353

}

354

355

interface CreateTokenOptions {

356

code: string;

357

state?: string;

358

redirectUrl?: string;

359

}

360

361

interface CreateTokenResult {

362

token: string;

363

scopes: string[];

364

tokenType: string;

365

}

366

367

interface CheckTokenOptions {

368

token: string;

369

}

370

371

interface CheckTokenResult {

372

token: string;

373

scopes: string[];

374

app: AppInfo;

375

user: UserInfo;

376

}

377

378

interface GetUserOctokitOptions {

379

token: string;

380

}

381

```

382

383

**Usage Examples:**

384

385

```typescript

386

import { OAuthApp } from "octokit";

387

388

// Create OAuth App

389

const oauthApp = new OAuthApp({

390

clientId: process.env.CLIENT_ID,

391

clientSecret: process.env.CLIENT_SECRET,

392

});

393

394

// Exchange code for token

395

const { token } = await oauthApp.createToken({

396

code: "code-from-oauth-callback",

397

});

398

399

// Get user client

400

const userOctokit = oauthApp.getUserOctokit({ token });

401

const user = await userOctokit.rest.users.getAuthenticated();

402

```

403

404

### Request Error Handling

405

406

Specialized error class for GitHub API request failures with detailed error information.

407

408

```typescript { .api }

409

class RequestError extends Error {

410

constructor(message: string, status: number, options: RequestErrorOptions);

411

412

// HTTP status code

413

status: number;

414

415

// Request details

416

request: {

417

method: string;

418

url: string;

419

headers: Record<string, string>;

420

};

421

422

// Response details (if available)

423

response?: {

424

status: number;

425

url: string;

426

headers: Record<string, string>;

427

data?: any;

428

};

429

}

430

431

interface RequestErrorOptions {

432

request: {

433

method: string;

434

url: string;

435

headers: Record<string, string>;

436

};

437

response?: {

438

status: number;

439

url: string;

440

headers: Record<string, string>;

441

data?: any;

442

};

443

}

444

```

445

446

**Usage Examples:**

447

448

```typescript

449

import { Octokit, RequestError } from "octokit";

450

451

const octokit = new Octokit({ auth: "invalid-token" });

452

453

try {

454

await octokit.rest.users.getAuthenticated();

455

} catch (error) {

456

if (error instanceof RequestError) {

457

console.log(`GitHub API error: ${error.status} ${error.message}`);

458

console.log(`Request: ${error.request.method} ${error.request.url}`);

459

460

if (error.status === 401) {

461

console.log("Authentication failed - check your token");

462

} else if (error.status === 403) {

463

console.log("Rate limit exceeded or insufficient permissions");

464

}

465

}

466

}

467

```

468

469

### Node.js Middleware

470

471

Express.js middleware for handling GitHub webhooks and OAuth flows in Node.js applications.

472

473

```typescript { .api }

474

function createNodeMiddleware(

475

app: App,

476

options?: NodeMiddlewareOptions

477

): (req: any, res: any, next?: Function) => void;

478

479

interface NodeMiddlewareOptions {

480

pathPrefix?: string;

481

onUnhandledRequest?: (req: any, res: any) => void;

482

}

483

```

484

485

**Usage Examples:**

486

487

```typescript

488

import express from "express";

489

import { App, createNodeMiddleware } from "octokit";

490

491

const app = new App({

492

appId: 123456,

493

privateKey: process.env.PRIVATE_KEY,

494

webhooks: { secret: process.env.WEBHOOK_SECRET },

495

});

496

497

const expressApp = express();

498

expressApp.use(createNodeMiddleware(app));

499

expressApp.listen(3000);

500

501

// Webhooks will be handled at POST /api/github/webhooks

502

// OAuth callback at GET /api/github/oauth/callback

503

```

504

505

## Types

506

507

### Pagination Types

508

509

Types for GraphQL pagination handling.

510

511

```typescript { .api }

512

interface PageInfoForward {

513

hasNextPage: boolean;

514

endCursor?: string;

515

}

516

517

interface PageInfoBackward {

518

hasPreviousPage: boolean;

519

startCursor?: string;

520

}

521

```

522

523

### Authentication Types

524

525

```typescript { .api }

526

interface Authentication {

527

type: "token" | "app" | "installation" | "oauth-app" | "oauth-user";

528

token: string;

529

tokenType?: "oauth" | "installation";

530

installationId?: number;

531

permissions?: Record<string, string>;

532

repositoryIds?: number[];

533

singleFileName?: string;

534

}

535

536

interface AuthInterface {

537

(): Promise<Authentication>;

538

}

539

540

interface AuthOptions {

541

appId?: number;

542

privateKey?: string;

543

installationId?: number;

544

clientId?: string;

545

clientSecret?: string;

546

token?: string;

547

}

548

```

549

550

## Error Handling

551

552

Common error scenarios and handling patterns:

553

554

- **401 Unauthorized**: Invalid or expired authentication token

555

- **403 Forbidden**: Rate limit exceeded or insufficient permissions

556

- **404 Not Found**: Repository, user, or resource doesn't exist

557

- **422 Unprocessable Entity**: Validation errors in request data

558

559

All API methods can throw `RequestError` instances that provide detailed error information including HTTP status codes, request details, and response data when available.