Search code examples
javascriptnode.jstwitter

Node.js Twitter API always returns 401 or 403 when trying to stream tweets


I've been trying to use the node package Twitter to stream, and then process the tweets for further use but am, apparently, already failing at authorization because every time I do try to access the stream I get a 401 or 403 response from the server.

I've tried these two ways of authenticating

const Twitter = require('twitter');

const twitterAPIKey = process.env.TWITTER_API_KEY;
const twitterAPIKeySecret = process.env.TWITTER_API_KEY_SECRET;
const twitterAccessToken = process.env.TWITTER_ACCESS_TOKEN;
const twitterAccessTokenSecret = process.env.TWITTER_ACCESS_TOKEN_SECRET;
const bearerToken = process.env.TWITTER_BEARER_TOKEN;

const users = [
    '2898008473'
]

const twitterClient = new Twitter({
    consumer_key:           twitterAPIKey,
    consumer_secret:        twitterAPIKeySecret,
    bearer_token:           bearerToken
});

const stream = twitterClient.stream('statuses/filter', {follow: users}, function(stream) {
   stream.on('data', function (data) {
       console.log(data);
   });

   stream.on('error', function (error) {
       console.log(error);
   });
});

This is the current iteration of my code, previously I've also tried running the authentication as follows

const twitterClient = new Twitter({
    consumer_key:           twitterAPIKey,
    consumer_secret:        twitterAPIKeySecret,
    access_token:           twitterAccessToken,
    access_token_secret:    twitterAccessTokenSecret
});

With no success so far. My project has been approved for elevated access and I even generated new keys after that just to make sure everything would work correctly.


Solution

  • The error is probably not in your Auth code.

    If this app was created after mid-2022 you no longer have access to v1.1 statuses/filter (regardless of elevated access) as it is being retired. Use the V2 filtered stream instead.