0

I'm working on a Next.JS app which will retrieve a list of tweets by hashtag (ideally, by hashtag between a start and end date, but one step at a time.)

Sadly, this all errors out. Process.env variables work.

fetch is isomorphic-unfetch. I think the problem is that I'm just not setting the headers correctly - what do you think?

edited for latest tools.

Tasks.getInitialProps = async function() {
  const authString: string = encodeURIComponent(
    [
      "OAuth",
      `oauth_consumer_key="${process.env.TWITTER_API_KEY}",`,
      `oauth_token="${process.env.TWITTER_TOKEN}",`,
      `oauth_nonce="${Math.random().toString}",`,
      `oauth_timestamp="${Date.now()}",`,
      `oauth_signature_method="HMAC-SHA1",`,
      `oauth_version="1.0"`
    ].join(" ")
  );
  try {
    console.log(authString); // looks good.
    const res = await fetch(
      "https://api.twitter.com/1.1/search/tweets.json?q=%23hometasking",
      {
        method: "get",
        headers: {
          authorization: authString
        }
      }
    );
    const data = await res.json();
    console.log(data);
    return {
      entries: { tweets: data }
    };
  } catch (err) {
    console.error(err);
    return { entries: { tweets: err } };
  }
};

Error in the console (server side:)

{ errors: [ { code: 215, message: 'Bad Authentication data.' } ] }
Brian Boyko
  • 613
  • 6
  • 15
  • 1
    Requests to Twitter API endpoints from frontend JavaScript code running in a browser aren’t going to succeed — due to the fact that the Twitter API is intentionally not CORS-enabled. The requests and responses need to instead be handled from backend code. – sideshowbarker Mar 24 '20 at 07:32
  • I'm using Next.JS so this is server-side, no? – Brian Boyko Mar 24 '20 at 11:36
  • You probably want to update the question and paste in the exact errors that the runtime is logging in the console or backend logs. And unless you’re seeing errors logged by the browser in devtools console, then the problem has nothing to do with CORS. The same-origin policy in only enforced by browsers — and cross-origin restrictions are only enforced by browsers. And CORS is strictly just a way to get browsers to relax restrictions on frontend code. – sideshowbarker Mar 24 '20 at 22:16
  • It's not much. { errors: [ { code: 215, message: 'Bad Authentication data.' } ] } – Brian Boyko Mar 24 '20 at 23:43

0 Answers0