Registry / http-networking / twitter-api-v2

twitter-api-v2

JSON →
library1.29.0jsnpmunverified

twitter-api-v2 is a strongly typed, full-featured, and lightweight client for both Twitter API v1.1 and v2, designed for Node.js. Currently at version 1.29.0, it maintains an active release cadence, frequently incorporating new API features, fixes, and improvements as seen in recent updates like adding `article` tweet fields and expanding user/community fields. Its key differentiators include comprehensive TypeScript typings for all request parameters and response payloads, ensuring robust development, and a remarkable zero-dependency footprint, leading to a minimal bundle size (23kb minified+gzipped). The library provides extensive support for streaming, pagination, user-context authentication with OAuth2, and convenient media upload helpers, contrasting with other libraries that often lack strong typing or carry numerous external dependencies. It aims to provide a reliable and efficient wrapper around Twitter's evolving API.

npm install twitter-api-v2
INSTALL
IMPORT
SIG · TWITTER-API-V2
T
twitter-api-v2
http-networkingjavascriptv1.29.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

TwitterApi
import { TwitterApi } from 'twitter-api-v2';
const TwitterApi = require('twitter-api-v2');
This is the main class for instantiating a Twitter client, supporting various authentication methods (Bearer token, OAuth1.1, OAuth2.0 user-context). While CommonJS `require` might work in some setups, native ESM import is the idiomatic way in modern Node.js.
TwitterApiReadOnly
import { TwitterApiReadOnly } from 'twitter-api-v2';
import TwitterApiReadOnly from 'twitter-api-v2';
Used primarily in TypeScript for type-hinting a client instance as read-only, preventing accidental write operations. It's usually created from an existing `TwitterApi` instance via `.readOnly` property.
ETwitterStreamEvent
import { ETwitterStreamEvent } from 'twitter-api-v2';
const ETwitterStreamEvent = require('twitter-api-v2').ETwitterStreamEvent;
An enum containing events emitted by the Twitter API v2 streaming client, such as 'data', 'tweet drop', or 'connection error', crucial for handling stream lifecycle and data.
TweetV2
import { TweetV2 } from 'twitter-api-v2';
import { TweetV2 } from 'twitter-api-v2/dist/types';
Represents the type definition for a Twitter API v2 Tweet object, useful for type-checking responses or constructing tweet objects in TypeScript. All core types are directly exported from the main package entry point.

This quickstart demonstrates how to instantiate a Twitter client with OAuth1.1, fetch user data via the v2 API, post a tweet, and listen to a sample stream, showcasing common library features.

import { TwitterApi, ETwitterStreamEvent } from 'twitter-api-v2'; const YOUR_APP_KEY = process.env.TWITTER_APP_KEY ?? ''; const YOUR_APP_SECRET = process.env.TWITTER_APP_SECRET ?? ''; const YOUR_ACCESS_TOKEN = process.env.TWITTER_ACCESS_TOKEN ?? ''; const YOUR_ACCESS_SECRET = process.env.TWITTER_ACCESS_SECRET ?? ''; async function main() { // Instantiate a client with OAuth1.1 user context for write operations const client = new TwitterApi({ appKey: YOUR_APP_KEY, appSecret: YOUR_APP_SECRET, accessToken: YOUR_ACCESS_TOKEN, accessSecret: YOUR_ACCESS_SECRET, }); // Get a read-only client for type safety const readOnlyClient = client.readOnly; try { // Fetch user by username using v2 API const user = await readOnlyClient.v2.userByUsername('twitterdev'); console.log(`Found user: ${user.data.name} (@${user.data.username})`); // Post a tweet using v2 API const { data: tweeted } = await client.v2.tweet('Hello from twitter-api-v2! 👋'); console.log(`Tweeted: ${tweeted.text} (ID: ${tweeted.id})`); // Example of streaming (listen for connection events) const stream = await readOnlyClient.v2.sampleStream(); stream.on(ETwitterStreamEvent.ConnectionError, err => console.error('Connection error:', err)); stream.on(ETwitterStreamEvent.Data, data => console.log('Stream data received:', data)); setTimeout(() => { stream.close(); console.log('Stream closed after 10 seconds.'); }, 10000); } catch (error) { console.error('An error occurred:', error); } } main();
Debug
Known issues
breakingVersion 1.22.0 introduced breaking changes related to how V2 Media Alt Text is handled during media uploads. Existing implementations for adding alternative text to media might need adjustment.
fix
Review the media upload methods, specifically `v2.uploadMedia` or related functions, to ensure compatibility with the updated alt text parameters and structure. Consult the changelog or documentation for specific adjustments required.
affects: >=1.22.0
gotchaThe underlying Twitter (X) API is subject to frequent and often unannounced changes, deprecations, and policy shifts, especially since recent platform changes. This can lead to unexpected API behavior or endpoint deprecations that are outside the library's control.
fix
Actively monitor official Twitter/X developer documentation and announcements. Keep `twitter-api-v2` updated to the latest version, as the maintainers actively adapt to changes. Implement robust error handling for API responses.
affects: >=1.0.0
gotchaIncorrect or insufficient OAuth scopes (permissions) granted to your application's access token can lead to '403 Forbidden' errors for specific API actions, even if the token itself is valid.
fix
Always verify that your application has been granted the necessary OAuth scopes for every API endpoint you intend to use. Re-authenticate or regenerate tokens if scopes need to be updated. For example, posting tweets requires 'tweet.write' scope.
affects: >=1.0.0
gotchaLike all API clients, this library does not automatically handle Twitter's API rate limits. Exceeding these limits will result in '429 Too Many Requests' errors and temporary blocks.
fix
Implement custom rate limit handling logic, including retries with exponential backoff. The library provides access to `x-rate-limit` headers in responses, which can be used to inform your rate limiting strategy.
affects: >=1.0.0
Errors
Common errors & fixes
Twitter API error: 401 Unauthorized
The provided API keys or access tokens are invalid, expired, or malformed.
fix
Verify that your `appKey`, `appSecret`, `accessToken`, and `accessSecret` are correct, up-to-date, and have not been revoked. Regenerate them if unsure.
Twitter API error: 403 Forbidden - You are not authorized to perform this action.
Your application's access token lacks the required OAuth scopes (permissions) for the API endpoint you are trying to access.
fix
Check the official Twitter API documentation for the specific endpoint to determine the necessary OAuth scopes (e.g., `tweet.write`, `users.read`). Ensure your application's token has these scopes granted.
Twitter API error: 429 Too Many Requests
Your application has exceeded the allowed number of requests for a specific API endpoint within a given time window (rate limit).
fix
Implement rate limiting logic on your side, such as retries with exponential backoff. You can inspect `x-rate-limit` headers in the API response to determine remaining calls and reset times.
Upgrade
Version history
1.29.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
1
Resources
twitter-api-v2 — npm install twitter-api-v2 · libregistry