Skip to content

Commit da673b7

Browse files
authored
docs: fix wrong snippets, add a credentials guide and common errors (#654)
* docs: fix wrong snippets, add a credentials guide and common errors * docs: soften the untested runtimes and the undocumented 402 * docs(streaming): close leftover connections with terminateAllStreamConnections()
1 parent cd59930 commit da673b7

13 files changed

Lines changed: 256 additions & 67 deletions

‎README.md‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,19 +40,33 @@ Here's a quick example of usage:
4040
```ts
4141
import { TwitterApi } from 'twitter-api-v2';
4242

43-
// Instantiate with desired auth type (here's Bearer v2 auth)
44-
const twitterClient = new TwitterApi('<YOUR_APP_USER_TOKEN>');
45-
46-
// Tell typescript it's a readonly app
47-
const readOnlyClient = twitterClient.readOnly;
43+
// OAuth 1.0a with the 4 keys of your app, to act as your own account.
44+
// You find them in the X Developer Console, under "Keys and tokens".
45+
const twitterClient = new TwitterApi({
46+
appKey: '<API_KEY>',
47+
appSecret: '<API_KEY_SECRET>',
48+
accessToken: '<ACCESS_TOKEN>',
49+
accessSecret: '<ACCESS_TOKEN_SECRET>',
50+
});
4851

4952
// Play with the built in methods
50-
const user = await readOnlyClient.v2.userByUsername('plhery');
53+
const { data: user } = await twitterClient.v2.userByUsername('plhery');
5154
await twitterClient.v2.tweet('Hello, this is a test.');
5255
// You can upload media easily!
53-
await twitterClient.v2.uploadMedia('./big-buck-bunny.mp4', { media_type: 'video/mp4' });
56+
const mediaId = await twitterClient.v2.uploadMedia('./big-buck-bunny.mp4', { media_type: 'video/mp4' });
57+
await twitterClient.v2.tweet({ text: 'Look at this video!', media: { media_ids: [mediaId] } });
58+
59+
// To only read public data, the app's bearer token is enough (it can't post)
60+
const appOnlyClient = new TwitterApi('<BEARER_TOKEN>');
61+
const { data: tweet } = await appOnlyClient.v2.singleTweet('20');
5462
```
5563

64+
Not sure which credentials you need? See [which credentials to use](./doc/auth.md#which-credentials-to-use).
65+
66+
A few things to know before you start:
67+
- The X API is pay-per-use: there's no free tier, and every read and write is billed. See [X pricing](https://docs.x.com/x-api/getting-started/pricing), and set a spending limit in the Developer Console while you test.
68+
- `twitter-api-v2` is made for Node.js. It should also run on Deno and Bun through their Node.js compatibility, but not in browsers or React Native. See [supported runtimes](./doc/basics.md#supported-runtimes).
69+
5670
## Why?
5771

5872
Sometimes, you just want to quickly bootstrap an application using the Twitter API.
@@ -104,7 +118,9 @@ Learn how to use the full potential of `twitter-api-v2`.
104118

105119
- Get started
106120
- [Create a client and make your first request](./doc/basics.md)
121+
- [Choose which credentials to use](./doc/auth.md#which-credentials-to-use)
107122
- [Handle Twitter authentication flows](./doc/auth.md)
123+
- [Fix common errors (401, 402, 403, 429)](./doc/errors.md#common-errors)
108124
- [Explore some examples](./doc/examples.md)
109125
- [Use and create plugins](./doc/plugins.md)
110126
- Use endpoints wrappers — ensure typings of request & response

‎doc/ads.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ The `twitter-api-v2` package includes experimental support for the Twitter Ads A
66
77
## Authentication & Base URL
88

9-
The Ads API uses the same OAuth flows as the main client. Create a `TwitterApi` instance with your credentials and access the Ads client through `client.ads`.
9+
The Ads API only accepts OAuth 1.0a user context: your app keys, plus the access token and secret of an account that can use the ads account.
10+
Create a `TwitterApi` instance with these credentials and access the Ads client through `client.ads`.
1011

1112
The client automatically prefixes requests with the appropriate Ads API base URL, so you don't need to manage the base URL yourself.
1213

1314
```ts
1415
import { TwitterApi } from 'twitter-api-v2';
1516

16-
const client = new TwitterApi({ /* your app credentials */ });
17+
const client = new TwitterApi({ appKey, appSecret, accessToken, accessSecret });
1718

1819
// Access the Ads API
1920
const adsClient = client.ads;

‎doc/auth.md‎

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,42 @@ inside `twitter-api-v2` package.
55

66
Please first see the [Basics](./basics.md) to know how to create a client with your application keys.
77

8-
***First***, you must know which type of authentication you want to use.
8+
## Which credentials to use
9+
10+
Your app's credentials are in the [X Developer Console](https://console.x.com), under "Keys and tokens".
11+
Which ones you need depends on what you want to do:
12+
13+
| You want to | Use | Client |
14+
| --- | --- | --- |
15+
| Read public data (search, users, timelines), use the filtered stream | App-only auth: the app's **Bearer Token** | `new TwitterApi(BEARER_TOKEN)` |
16+
| Act as your own account (a personal bot, your own automation) | OAuth 1.0a: the **API Key & Secret**, plus the **Access Token & Secret** generated in the console | `new TwitterApi({ appKey, appSecret, accessToken, accessSecret })` |
17+
| Act on behalf of other users | [OAuth 2.0 with scopes](#oauth2-user-wide-authentication-flow) (recommended by X), or the [3-legged OAuth 1.0a flow](#user-wide-authentication-flow) | `new TwitterApi(USER_ACCESS_TOKEN)`, or the 4 OAuth 1.0a keys |
18+
| Use the [Ads API](./ads.md) | OAuth 1.0a | `new TwitterApi({ appKey, appSecret, accessToken, accessSecret })` |
19+
20+
How the console names map to the client fields:
21+
- API Key and API Key Secret (also called consumer key and secret): `appKey` and `appSecret`
22+
- Access Token and Access Token Secret: `accessToken` and `accessSecret`. The ones generated in the console belong to the account that owns the app.
23+
- Bearer Token: the string given to `new TwitterApi()`
24+
- Client ID and Client Secret: `clientId` and `clientSecret`. They are only used to run the OAuth 2.0 flow and refresh its tokens, they can't call the API by themselves.
25+
26+
What often goes wrong:
27+
- **The bearer token is read-only.** It identifies your app, not a user, so it can't post, like, send DMs or call `v2.me()`:
28+
X answers with a 403 "Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint".
29+
An OAuth 2.0 *user* access token is also given to `new TwitterApi()` as a string, but it acts as that user.
30+
- **Writing with OAuth 1.0a needs "Read and write" app permissions.** Set them in your app's user authentication settings,
31+
then regenerate the access token and secret: tokens keep the permissions they were created with.
32+
- **OAuth 2.0 tokens only get the scopes you asked for.** Most endpoints need `tweet.read` and `users.read`, posting needs `tweet.write` too,
33+
uploading media needs `media.write`, and you need `offline.access` to get a refresh token.
34+
X lists the scopes of every endpoint in its [authentication mapping](https://docs.x.com/fundamentals/authentication/guides/v2-authentication-mapping).
35+
To add a scope, send the user through the flow again.
36+
- **Some endpoints only accept one kind of auth.** For example, the filtered stream only works with the bearer token,
37+
so a bot that streams tweets and replies to them needs two clients (see [this example](./examples.md#stream-tweets-in-real-time)).
38+
39+
If you get a 401 or 403 anyway, see [common errors](./errors.md#common-errors).
40+
41+
## Authentication flows
42+
43+
The rest of this page explains each flow:
944

1045
- User authentication (3-legged OAuth 1.0a flow, see [User-wide authentication flow](#user-wide-authentication-flow))
1146
- App-only authentication (Bearer token, see [Application-only authentication flow](#application-only-authentication-flow))
@@ -19,7 +54,10 @@ Please first see the [Basics](./basics.md) to know how to create a client with y
1954
Many endpoints on the Twitter developer platform use the OAuth 1.0a method to act on behalf of a Twitter account.
2055
For example, if you have a Twitter developer app, you can make API requests on behalf of any Twitter account as long as that user authenticates your app.
2156

22-
This method is **fairly the most complex** of authentication flow options, but it is, at least for now, the **most used method across Twitter API**.
57+
This method is **fairly the most complex** of authentication flow options.
58+
X now recommends [OAuth 2.0](#oauth2-user-wide-authentication-flow) to act on behalf of users, but OAuth 1.0a still works with v2 endpoints, and the Ads API only accepts OAuth 1.0a.
59+
60+
**Note**: If you only need to act as your own account, you don't need this flow: generate the access token and secret in the Developer Console.
2361

2462
It is named "3-legged" because it is split in 3 parts:
2563
1. You (the app/server) generate a auth link that is clickable by a external user, and gives you *temporary* access tokens
@@ -43,6 +81,7 @@ const client = new TwitterApi({ appKey: CONSUMER_KEY, appSecret: CONSUMER_SECRET
4381

4482
To create the authentication link, use `client.generateAuthLink()` method.
4583
**If you choose to redirect users to your website after authentication, you need to provide a callback URL here.**
84+
It must be one of the callback URLs registered in your app's user authentication settings. Use `'oob'` instead for the PIN flow.
4685
```ts
4786
const authLink = await client.generateAuthLink(CALLBACK_URL);
4887

@@ -161,7 +200,7 @@ const client = new TwitterApi({ username: MY_USERNAME, password: MY_PASSWORD });
161200

162201
## OAuth2 user-wide authentication flow
163202

164-
Alternatively of OAuth 1.0a method, you can use OAuth2 user-context, which is restricted to **v2 of Twitter API**.
203+
OAuth2 user-context is the method X recommends to act on behalf of users. It only works with **v2 of Twitter API**.
165204
This process is very similar of one used in OAuth 1.0a, so it's recommended to read it first to understand what's happening below.
166205

167206
The main advantage of this method is that you can **explicitly specify which part of data you'll need from the Twitter user's account**.
@@ -181,18 +220,20 @@ This authentication is split into 3 parts:
181220
### Create the auth link
182221

183222
You need to have a client instantiated with your **client keys** from Twitter.
184-
If you've declared app as "public" app, you only need your **client ID**, if you've declared app as "confidential" app, you will need **client ID and client secret**.
223+
If you've declared app as "public" app (Native App or Single page App), you only need your **client ID**,
224+
if you've declared app as "confidential" app (Web App, Automated App or Bot), you will need **client ID and client secret**.
185225

186226
```ts
187227
const client = new TwitterApi({ clientId: CLIENT_ID, clientSecret: CLIENT_SECRET });
188228
```
189229

190230
To create the authentication link, use `client.generateOAuth2AuthLink()` method.
191-
**You need to provide a callback URL here.**
231+
**You need to provide a callback URL here.** It must exactly match one of the callback URLs registered in your app's user authentication settings.
192232
```ts
233+
// Ask for every scope your app needs: 'tweet.write' to post, 'media.write' to upload media, etc.
193234
// Don't forget to specify 'offline.access' in scope list if you want to refresh your token later
194235
// Include 'users.email' if you need to access user's email address
195-
const { url, codeVerifier, state } = client.generateOAuth2AuthLink(CALLBACK_URL, { scope: ['tweet.read', 'users.read', 'users.email', 'offline.access', ...] });
236+
const { url, codeVerifier, state } = client.generateOAuth2AuthLink(CALLBACK_URL, { scope: ['tweet.read', 'tweet.write', 'users.read', 'offline.access'] });
196237

197238
// Redirect your user to {url}, store {state} and {codeVerifier} into a DB/Redis/memory after user redirection
198239
```
@@ -250,6 +291,8 @@ The `.loginWithOAuth2()` method already returns a logged client, but if you want
250291
const client = new TwitterApi('<YOUR-ACCESS-TOKEN>');
251292
```
252293

294+
Access tokens expire after two hours (`expiresIn` is in seconds). To keep acting for the user, refresh them as shown below.
295+
253296
### Optional: refresh the token later
254297

255298
If you choose to include `'offline.access'` as scope, you can store and re-use later `refreshToken` when `expiresIn` time kicks in.
@@ -284,3 +327,15 @@ await oauth2Client.v2.me();
284327
```
285328

286329
Exchanging the same OAuth 1.0a token again gives a new token pair and invalidates the previous one.
330+
331+
### Troubleshooting the OAuth2 flow
332+
333+
If the authorization page shows an error, or `.loginWithOAuth2()` fails with "Value passed for the authorization code was invalid":
334+
- **Exchange each code only once.** A code works once, and only for 30 seconds. If your callback runs twice, the second exchange fails:
335+
React StrictMode runs effects twice in development, and reloading the callback page sends the same code again.
336+
Exchange the code on your server, once, and store the tokens.
337+
- **Use the `codeVerifier` and `state` of the link the user clicked.** They come from the same `.generateOAuth2AuthLink()` call as its `url`.
338+
Generating a new link (on every page render, for example) gives a new `codeVerifier`, which won't work with the code of the previous link.
339+
- **Use the same callback URL everywhere.** The `redirectUri` given to `.loginWithOAuth2()` must be the one given to `.generateOAuth2AuthLink()`,
340+
and both must exactly match a callback URL of your app, scheme, port, path and trailing slash included.
341+
- **Redirect the browser to `url`, don't `fetch()` it.** It's a page where the user approves your app.

‎doc/basics.md‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@
44
> Feel free to convert them to regular JavaScript. If you don't use a transpiler,
55
> you might need to replace `import`s by `require()` calls.
66
7+
## Supported runtimes
8+
9+
`twitter-api-v2` is made for Node.js: it uses Node's `https`, `zlib`, `crypto` and `fs` modules.
10+
11+
- **Deno and Bun**: they should work through their Node.js compatibility, but we don't test them, so please open an issue if something breaks.
12+
- **Browsers and React Native**: not supported. Your keys would be visible to anyone, and X's API doesn't allow cross-origin requests anyway.
13+
Call the X API from your server, and let your front-end talk to your server.
14+
715
## Client basics
816

917
### Create a client
@@ -57,6 +65,9 @@ you can choose the right sub-client:
5765
- `Read-write`: `rwClient = client.readWrite`
5866
- `Read-only`: `roClient = client.readOnly`
5967

68+
This is optional, and it doesn't change any request: it only hides the methods you can't use from TypeScript and your IDE suggestions.
69+
What you can actually do depends on your credentials, see [which credentials to use](./auth.md#which-credentials-to-use).
70+
6071
## Authentication
6172

6273
Please see [Authentication part](./auth.md) of the doc.
@@ -98,14 +109,14 @@ If your network connection is behind a proxy and you are unable to make requests
98109

99110
```ts
100111
// Note: this package is an external package, it isn't bundled with Node.
101-
import * as HttpProxyAgent from 'https-proxy-agent';
112+
import { HttpsProxyAgent } from 'https-proxy-agent';
102113

103114
// HTTPS proxy to connect to
104115
// twitter-api-v2 will always use HTTPS
105116
const proxy = process.env.HTTP_PROXY || 'https://1.1.1.1:3000';
106117

107-
// create an instance of the `HttpProxyAgent` class with the proxy server information
108-
const httpAgent = new HttpProxyAgent(proxy);
118+
// create an instance of the `HttpsProxyAgent` class with the proxy server information
119+
const httpAgent = new HttpsProxyAgent(proxy);
109120

110121
// Instantiate helper with the agent
111122
const client = new TwitterApi('<bearerToken>', { httpAgent });

‎doc/errors.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,61 @@ TwitterApiV2Settings.logger = {
118118
},
119119
};
120120
```
121+
122+
## Common errors
123+
124+
X explains why a request failed in the response body, which you find in `error.data`.
125+
The error message doesn't always include it, so log `error.data` first:
126+
127+
```ts
128+
import { ApiResponseError } from 'twitter-api-v2';
129+
130+
try {
131+
await client.v2.tweet('Hello!');
132+
} catch (error) {
133+
if (error instanceof ApiResponseError) {
134+
console.log(error.code, error.data);
135+
}
136+
}
137+
```
138+
139+
### 401 Unauthorized
140+
141+
X doesn't accept your credentials:
142+
- A key or token is wrong or empty. Check that your environment variables are loaded.
143+
- You regenerated your keys or tokens in the Developer Console, which revokes the old ones.
144+
- Your OAuth 2.0 user access token expired (they last two hours): [refresh it](./auth.md#optional-refresh-the-token-later).
145+
146+
### 402 Payment Required
147+
148+
Your account probably ran out of credits. X blocks requests when your credit balance is used up, or when you reach the spending limit set in the Developer Console,
149+
until you add credits or the next billing cycle starts. X doesn't document which status code it sends then, but users report a 402. See [X pricing](https://docs.x.com/x-api/getting-started/pricing).
150+
151+
### 403 Forbidden
152+
153+
Your credentials are valid, but they don't allow this request. `error.data.detail` usually tells you why:
154+
- **"Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint"**: you used the bearer token (or `.appLogin()`) for an endpoint that acts as a user, like posting or `v2.me()`.
155+
Use OAuth 1.0a user keys or an OAuth 2.0 user token, see [which credentials to use](./auth.md#which-credentials-to-use).
156+
- **"Authenticating with Unknown is forbidden for this endpoint"**: X couldn't use the credentials you sent.
157+
Check that none of them is empty, then regenerate the access token and secret in the Developer Console.
158+
- **"Your client app is not configured with the appropriate oauth1 app permissions for this endpoint"**: your app is read-only.
159+
Set it to "Read and write" in its user authentication settings, then regenerate the access token and secret.
160+
- **A plain "Forbidden" with an OAuth 2.0 user token**: the token misses a scope this endpoint needs, like `tweet.write`, `media.write` or `dm.write`.
161+
Add it to your scopes, and send the user through the auth flow again.
162+
- **"client-not-enrolled"**, or a message saying your app must be attached to a Project: create your app inside a Project in the Developer Console,
163+
and check that your access includes this endpoint.
164+
- **"You currently have access to a subset of X API v2 endpoints..." (code 453)**: you called a v1.1 endpoint your access doesn't include. Use the v2 method instead.
165+
166+
### Requests X no longer allows
167+
168+
Some requests fail even with the right credentials and scopes, because X restricted them on self-serve (pay-per-use) plans:
169+
- Since February 23, 2026, you can only reply to a tweet when its author summoned you, by mentioning your account or quoting one of your posts.
170+
- Since April 20, 2026, following, liking and quoting are removed from self-serve plans.
171+
172+
Enterprise plans are not affected. See the [X changelog](https://docs.x.com/changelog).
173+
174+
### 429 Too Many Requests
175+
176+
You hit a rate limit, or a usage cap like the monthly cap of post reads.
177+
`error.rateLimitError` is `true`, and `error.rateLimit` tells you when the limit resets, see [rate limiting](./rate-limiting.md).
178+
If `error.rateLimit.day` or `error.rateLimit.userDay` has `remaining: 0`, you hit a 24-hour limit.

0 commit comments

Comments
 (0)