I am using a Cloudflare worker and this is what my index.ts file looks like:

const tweet = async () => {
  console.log('tweet function ran')
  let request = await fetch("https://api.twitter.com/2/tweets", {
    method: "POST",
    headers: {
      Authorization: "Bearer <ACCESS TOKEN HERE>",
      'user-agent': "v2CreateTweetJS",
      'content-type': "application/json",
      'accept': "application/json"
    },
    body: JSON.stringify({"text": "my remote Tweet"})
  })
  console.log(await request.json())
  return new Response("This response ran")
}

addEventListener('fetch', (event: FetchEvent) => {
  event.respondWith(tweet());
});

And when I run this code, I get this error:

<myusername>@<mycomputername> <myappname> % wrangler dev
👂  Listening on http://127.0.0.1:8787
🌀  Detected changes...
💁  Ignoring stale first change
tweet function ran
{ title: 'Unsupported Authentication', detail: 'Authenticating with OAuth 2.0 Application-Only is …OAuth 1.0a User Context, OAuth 2.0 User Context].', type: 'https://api.twitter.com/2/problems/unsupported-authentication', status: 403 }
[2022-04-23 21:41:58] GET <myappname>.<mycloudflarworkername>.workers.dev/ HTTP/1.1 200 OK
^C
<myusername>@<mycomputername> <myappname> % 

How do I fix this? I would be fine with switching to v1 APIs but I can’t find any info on how to do that either.

How did you generate the bearer token? Usually it’s application only, so cannot be used to POST. You need to use oauth1.0a (access token and secret) or oauth2 OAuth 2.0 Authorization Code Flow with PKCE | Docs | Twitter Developer Platform

1 Like

Yeah that was excatly the problem. I still don’t know how to post a Tweet though