You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit da673b7
Browse filesBrowse the repository at this point in the historyBrowse files
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()
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
+
56
70
## Why?
57
71
58
72
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`.
104
118
105
119
- Get started
106
120
-[Create a client and make your first request](./doc/basics.md)
121
+
-[Choose which credentials to use](./doc/auth.md#which-credentials-to-use)
Copy file name to clipboardExpand all lines: doc/ads.md
+3-2Lines changed: 3 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,14 +6,15 @@ The `twitter-api-v2` package includes experimental support for the Twitter Ads A
6
6
7
7
## Authentication & Base URL
8
8
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`.
10
11
11
12
The client automatically prefixes requests with the appropriate Ads API base URL, so you don't need to manage the base URL yourself.
12
13
13
14
```ts
14
15
import { TwitterApi } from'twitter-api-v2';
15
16
16
-
const client =newTwitterApi({ /* your app credentials */ });
Copy file name to clipboardExpand all lines: doc/auth.md
+61-6Lines changed: 61 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -5,7 +5,42 @@ inside `twitter-api-v2` package.
5
5
6
6
Please first see the [Basics](./basics.md) to know how to create a client with your application keys.
7
7
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:
9
44
10
45
- User authentication (3-legged OAuth 1.0a flow, see [User-wide authentication flow](#user-wide-authentication-flow))
11
46
- 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
19
54
Many endpoints on the Twitter developer platform use the OAuth 1.0a method to act on behalf of a Twitter account.
20
55
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.
21
56
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.
23
61
24
62
It is named "3-legged" because it is split in 3 parts:
25
63
1. You (the app/server) generate a auth link that is clickable by a external user, and gives you *temporary* access tokens
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**.
165
204
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.
166
205
167
206
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:
181
220
### Create the auth link
182
221
183
222
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**.
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
+
awaitclient.v2.tweet('Hello!');
132
+
} catch (error) {
133
+
if (errorinstanceofApiResponseError) {
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