Back to APIs

X (Twitter)

twitter.com

Schedule, update and delete posts on X.

Using the X (Twitter) API with Trigger.dev

You can use Trigger.dev with any existing Node SDK or even just using fetch. Using io.runTask makes your X (Twitter) background job resumable and appear in our dashboard.

Use io.runTask() and the official SDK or fetch.

Example code using X (Twitter)

Below is a working code example of how you can use X (Twitter) with Trigger.dev. These samples are open source and maintained by the community, you can copy and paste them into your own projects.

1
import { TriggerClient, eventTrigger } from "@trigger.dev/sdk";
2
import z from "zod";
3
import { createHmac } from "crypto";
4
import OAuth from "oauth-1.0a";
5
6
// Create tokens at
7
// https://developer.twitter.com/en/docs/twitter-api/getting-started/getting-access-to-the-twitter-api
8
const endpointURL = "https://api.twitter.com/2/tweets";
9
const token = {
10
key: process.env.X_ACCESS_TOKEN!,
11
secret: process.env.X_ACCESS_TOKEN_SECRET!,
12
};
13
14
// Using OAuth 1.0a
15
const oauth = new OAuth({
16
consumer: {
17
key: process.env.X_CONSUMER_KEY!,
18
secret: process.env.X_CONSUMER_SECRET!,
19
},
20
signature_method: "HMAC-SHA1",
21
hash_function: (baseString: string, key: string) =>
22
createHmac("sha1", key).update(baseString).digest("base64"),
23
});
24
25
// Create an authorization header
26
const authHeader = oauth.toHeader(
27
oauth.authorize({ url: endpointURL, method: "POST" }, token)
28
);
29
30
// Create request options
31
const requestOptions: RequestInit = {
32
method: "POST",
33
headers: {
34
Authorization: authHeader["Authorization"],
35
"user-agent": "v2CreateTweetJS",
36
"content-type": "application/json",
37
accept: "application/json",
38
},
39
};
40
41
client.defineJob({
42
id: "tweet-x",
43
name: "Tweet X",
44
version: "1.0.0",
45
trigger: eventTrigger({
46
name: "tweet-x",
47
schema: z.object({
48
text: z.string().max(280), // Tweets are limited to 280 characters
49
}),
50
}),
51
run: async (payload, io, ctx) => {
52
// Wrap an SDK call in io.runTask so it's resumable and displays in logs
53
await io.runTask(
54
"Tweet X",
55
async () => {
56
// Make request using Fetch API
57
return await fetch(endpointURL, {
58
...requestOptions,
59
body: JSON.stringify(payload),
60
}).then((response) => response.json());
61
},
62
63
// Add metadata to improve how the task displays in the logs
64
{ name: "Tweet X", icon: "twitter" }
65
);
66
},
67
});