A production-ready TypeScript library for fetching tweet data using Twitter's Syndication API.
- ✅ Type-safe: Full TypeScript support with comprehensive type definitions
- ✅ Production-ready: Error handling, timeouts, and proper error classes
- ✅ Modular: Clean separation of concerns with organized file structure
- ✅ Configurable: Customizable timeout, language, and base URL
- ✅ Multiple URL formats: Supports
twitter.com,x.com, andt.coURLs - ✅ Media parsing: Extracts photos and videos from tweets
- ✅ Error handling: Custom error classes for different failure scenarios
bun installimport { getTweetData } from './src';
const tweet = await getTweetData('https://x.com/username/status/1234567890');
console.log(tweet.text);
console.log(tweet.author.name);import { TweetService } from './src';
const service = new TweetService({
timeout: 15000, // 15 seconds
language: 'en',
});
const tweet = await service.getTweetData('https://x.com/username/status/1234567890');import { getTweetData, InvalidUrlError, TweetNotFoundError, ApiError } from './src';
try {
const tweet = await getTweetData(url);
} catch (error) {
if (error instanceof InvalidUrlError) {
console.error('Invalid URL');
} else if (error instanceof TweetNotFoundError) {
console.error('Tweet not found');
} else if (error instanceof ApiError) {
console.error('API error:', error.message);
}
}Convenience function to fetch tweet data.
Parameters:
tweetUrl: Twitter/X URL (supportstwitter.com,x.com, ort.co)config: Optional configuration object
Returns: Promise resolving to TweetData
Main service class for fetching tweets.
Constructor:
new TweetService(config?: TweetServiceConfig)Methods:
getTweetData(tweetUrl: string): Promise<TweetData>- Fetch tweet dataupdateConfig(config: Partial<TweetServiceConfig>): void- Update configuration
interface TweetServiceConfig {
timeout?: number; // Request timeout in ms (default: 10000)
language?: string; // Language code (default: 'en')
baseUrl?: string; // API base URL (default: Twitter's CDN)
}interface TweetData {
id: string;
url: string;
text: string;
created_at: string;
author: TweetAuthor;
metrics: TweetMetrics;
media: MediaItem[];
raw: SyndicationData; // Raw API response
}TweetError- Base error classInvalidUrlError- Invalid tweet URLTweetNotFoundError- Tweet not found or unavailableApiError- API request failedTimeoutError- Request timeout
.
├── src/
│ ├── api/ # API client
│ │ └── syndication-client.ts
│ ├── config/ # Configuration
│ │ └── index.ts
│ ├── errors/ # Custom error classes
│ │ └── index.ts
│ ├── services/ # Service layer
│ │ └── tweet-service.ts
│ ├── types/ # Type definitions
│ │ └── index.ts
│ ├── utils/ # Utility functions
│ │ ├── media-parser.ts
│ │ └── url-parser.ts
│ └── index.ts # Main entry point
├── examples/ # Example usage
│ └── main.ts
├── index.ts # Root entry point
└── package.json
bun run example
# or
bun run examples/main.tsStart the development server:
bun run dev
# or
bun run serverThe server will start on http://localhost:3000 (or the port specified in PORT environment variable).
GET /api
Returns service status and available endpoints.
GET /api/tweet-html?url=<tweet-url>&theme=<theme>&hide_media=<true|false>&font_size=<size>&width=<width>
Returns a beautiful, clean HTML render of the tweet with CSS, optimized for embedding.
Query Parameters:
url(required): The tweet URL to fetchtheme(optional):light,dark,dim, orblack(Default:light)accent_color(optional): Custom hero color (e.g.,#ff0000, Default:#1d9bf0)hide_media(optional): Set totrueto hide images and videoshide_metrics(optional): Set totrueto hide engagement countshide_footer(optional): Set totrueto hide the entire footerhide_border(optional): Set totrueto remove the outer card borderhide_timestamp(optional): Set totrueto hide the date/time linebg_transparent(optional): Set totruefor transparent backgroundfont_size(optional):small,medium, orlarge(Default:medium)width(optional): Custom CSS width, e.g.,500px(Default:550px)
Example:
curl "http://localhost:3000/api/tweet-html?url=https://x.com/username/status/123&theme=dim"GET /api/tweet-svg?url=<tweet-url>
Returns a high-quality vector SVG capture of the tweet.
Query Parameters:
url(required): The tweet URL to snapshot
Example:
curl "http://localhost:3000/api/tweet-svg?url=https://x.com/username/status/123"Success Response (200):
{
"success": true,
"data": {
"id": "1234567890",
"url": "https://twitter.com/username/status/1234567890",
"text": "Tweet content...",
"created_at": "2024-01-01T00:00:00Z",
"author": {
"id": "123",
"name": "User Name",
"username": "username",
"avatar": "https://...",
"verified": false
},
"metrics": {
"likes": 100,
"retweets": 50,
"replies": 25,
"quotes": 10
},
"media": []
}
}Error Responses:
400- Invalid URL:
{
"success": false,
"error": "INVALID_URL",
"message": "Invalid tweet URL: ..."
}404- Tweet Not Found:
{
"success": false,
"error": "TWEET_NOT_FOUND",
"message": "Tweet not found or unavailable"
}504- Timeout:
{
"success": false,
"error": "TIMEOUT",
"message": "Request exceeded timeout of 10000ms"
}500- API Error:
{
"success": false,
"error": "API_ERROR",
"message": "API request failed",
"statusCode": 500
}This project is configured for Vercel deployment with Bun runtime.
- Install Vercel CLI (if not already installed):
npm install -g vercel- Deploy:
vercelOr deploy to production:
vercel --prod- Environment Variables (optional): You can set environment variables in the Vercel dashboard:
PORT- Server port (default: 3000)
The project includes a vercel.json configuration file that:
- Uses Bun runtime (
vercel-bun@latest) for serverless functions - Routes all
/api/*requests to the API handler - Configures build and install commands
# Development mode with hot reload
bun run dev
# Production mode
bun run start# Type checking
bun run typecheck
# Start development server
bun run devMIT