When a request fails, you can catch a ApiRequestError, a ApiPartialResponseError or a ApiResponseError object (all instances of Error), that contain useful information about whats happening.
- An
ApiRequestErrorhappens when the request failed to sent (network error, bad URL...). - An
ApiPartialResponseErrorhappens the response has been partially sent, but the connection is closed (by you, the OS or Twitter), or when the response body can't be parsed or decompressed. - An
ApiResponseErrorhappens when Twitter replies with an error.
Some properties are common for both objects:
erroristruetypecontains eitherETwitterApiError.Request,ETwitterApiError.PartialResponseorETwitterApiError.Response(depending of error)requestcontaining node's rawClientRequestinstance
requestError, an instance ofErrorthat has been thrown throughrequest.on('error')handler
responseError, an instance ofErrorthat has been thrown byresponse.on('error')or by the tentative of parsing the response body, or that tells that the connection was closed before the end of the responseresponse, containing raw node'sIncomingMessageinstancerawContent, containing all the chunks received from distant server
data, containing parsed Twitter response data (type ofTwitterApiErrorData)codeis anumbercontaining the HTTP error code (401,404, ...)response, containing raw node'sIncomingMessageinstanceheaders, containingIncomingHttpHeadersrateLimit(can be undefined orTwitterRateLimit), containing parsed rate limit headers (if any)- (getter)
errors, direct access of parsed Twitter errors ((ErrorV1 | ErrorV2)[]orundefined) - (getter)
rateLimitError,trueif this error is fired because a rate limit has been hit - (getter)
isAuthError,trueif this error is fired because logged user cannot do this action (invalid token, invalid app rights...)
hasErrorCode(code: number | EApiV1ErrorCode | EApiV2ErrorCode): Tells if given Twitter error code is present in error response. v2 problem types are compared by their last part (likeinvalid-request), so thehttps://api.twitter.com/2/problems/…andhttps://api.x.com/2/problems/…forms match each other
Requests (that aren't used for streaming) natively support gzip/deflate compression.
If it causes issues, you can force compression to be disabled:
const client = new TwitterApi(tokens, { compression: false });If you want to debug a single request made through direct HTTP handlers .get/.post/.delete,
you can use an additional property named requestEventDebugHandler.
client.v2.get(
'tweets/search/recent',
{ query: 'nodeJS', max_results: 100 },
{ requestEventDebugHandler: (eventType, data) => console.log('Event', eventType, 'with data', data) },
)It takes a function of type (event: TRequestDebuggerHandlerEvent, data?: any) => void where available events are:
type TRequestDebuggerHandlerEvent = 'abort' | 'socket' | 'socket-error' | 'socket-connect'
| 'socket-close' | 'socket-end' | 'socket-lookup' | 'socket-timeout' | 'request-error'
| 'response' | 'response-aborted' | 'response-error' | 'response-close' | 'response-end';data parameter associated to events:
abort: None /abortevent ofrequestsocket:{ socket: Socket }/request.socketobject, when it is available throughrequest.on('socket')socket-error:{ socket: Socket, error: Error }/errorevent ofrequest.socketsocket-connect:{ socket: Socket }/connectevent ofrequest.socketsocket-close:{ socket: Socket, withError: boolean }/closeevent ofrequest.socketsocket-end:{ socket: Socket }/endevent ofrequest.socketsocket-lookup:{ socket: Socket, data: [err: Error?, address: string, family: string | number, host: string] }/lookupevent ofrequest.socketsocket-timeout:{ socket: Socket }/timeoutevent ofrequest.socketrequest-error:{ requestError: Error }/errorevent ofrequestresponse:{ res: IncomingMessage }/responseobject, when it is available throughrequest.on('response')response-aborted:{ error?: Error }/abortedevent ofresponseresponse-error:{ error: Error }/errorevent ofresponseresponse-close:{ data: string }(raw response data) /closeevent ofresponseresponse-end: None /endevent ofresponse
If you keep obtaining errors and you don't know how to obtain the response data, or you want to see exactly what have been sent to Twitter, you can enable the debug mode:
import { TwitterApiV2Settings } from 'twitter-api-v2';
TwitterApiV2Settings.debug = true;By default, all requests and responses will be printed to console.
You can customize the output by implementing your own debug logger:
// Here's the default logger:
TwitterApiV2Settings.logger = {
log: (msg, payload) => console.log(msg, payload),
};
// .logger follows this interface:
interface ITwitterApiV2SettingsLogger {
log(message: string, payload?: any): void;
}
// An example for a file logger
import * as fs from 'fs';
import * as util from 'util';
const destination = fs.createWriteStream('requests.log', { flags: 'a' });
TwitterApiV2Settings.logger = {
log: (msg, payload) => {
if (payload) {
const strPayload = util.inspect(payload);
destination.write(msg + ' ' + strPayload);
} else {
destination.write(msg);
}
},
};X explains why a request failed in the response body, which you find in error.data.
The error message doesn't always include it, so log error.data first:
import { ApiResponseError } from 'twitter-api-v2';
try {
await client.v2.tweet('Hello!');
} catch (error) {
if (error instanceof ApiResponseError) {
console.log(error.code, error.data);
}
}X doesn't accept your credentials:
- A key or token is wrong or empty. Check that your environment variables are loaded.
- You regenerated your keys or tokens in the Developer Console, which revokes the old ones.
- Your OAuth 2.0 user access token expired (they last two hours): refresh it.
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, 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.
Your credentials are valid, but they don't allow this request. error.data.detail usually tells you why:
- "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 orv2.me(). Use OAuth 1.0a user keys or an OAuth 2.0 user token, see which credentials to use. - "Authenticating with Unknown is forbidden for this endpoint": X couldn't use the credentials you sent. Check that none of them is empty, then regenerate the access token and secret in the Developer Console.
- "Your client app is not configured with the appropriate oauth1 app permissions for this endpoint": your app is read-only. Set it to "Read and write" in its user authentication settings, then regenerate the access token and secret.
- A plain "Forbidden" with an OAuth 2.0 user token: the token misses a scope this endpoint needs, like
tweet.write,media.writeordm.write. Add it to your scopes, and send the user through the auth flow again. - "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, and check that your access includes this endpoint.
- "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.
Some requests fail even with the right credentials and scopes, because X restricted them on self-serve (pay-per-use) plans:
- 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.
- Since April 20, 2026, following, liking and quoting are removed from self-serve plans.
Enterprise plans are not affected. See the X changelog.
You hit a rate limit, or a usage cap like the monthly cap of post reads.
error.rateLimitError is true, and error.rateLimit tells you when the limit resets, see rate limiting.
If error.rateLimit.day or error.rateLimit.userDay has remaining: 0, you hit a 24-hour limit.