0x01

For some reason, I can't access Twitter's API directly, therefore, I need a relay.

There are a bunch of "Wheels" for twitter API that you can use in Node.js, BUT sadly, they won't work with Worker.

0x02

This section will shows the key parts of how to tweet by using Twitter API 2.0 from CloudFlare Worker.

wrangler.toml

Add this line to enable nodejs compatibility

1
node_compat = true

Import

1
2
import OAuth from 'oauth-1.0a';
import { HmacSHA1, enc } from 'crypto-js';

Authentication

It's recommended to use wrangler to manage your api keys

1
2
3
4
5
6
7
8
9
10
11
12
13
14
oauth = OAuth({
consumer: {
key: env.TWITTER_API_KEY,
secret: env.TWITTER_API_SECRET
},
signature_method: 'HMAC-SHA1',
hash_function(baseString, key) {
return HmacSHA1(baseString, key).toString(enc.Base64);
},
});
oauthToken = {
key: env.TWITTER_AUTH_TOKEN,
secret: env.TWITTER_AUTH_SECRET,
};

Call API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const endPoint = "https://api.twitter.com/2/tweets"

const authHeader = oauth.toHeader(oauth.authorize({
url: endPoint,
method: 'POST'
}, oauthToken));

const response = await fetch(endPoint, {
method: "POST",
headers: {
Authorization: authHeader["Authorization"],
'Content-Type': 'application/json',
},
body: JSON.stringify({
"text": "Greeting from Worker!"
}),
});