Next.js Discord

Discord Forum

api routing best way to fetch latest tweets from twitter account

Unanswered
English Angora posted this in #help-forum
Open in Discord
English AngoraOP
I created api/tweets/route.ts
import { NextApiRequest, NextApiResponse } from "next";
import axios from "axios";

let cachedTweets: any = null;
let lastFetchTime: number | null = null;
const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "GET") {
    res.setHeader("Allow", ["GET"]);
    return res.status(405).end(`Method ${req.method} Not Allowed`);
  }

  if (
    cachedTweets &&
    lastFetchTime &&
    Date.now() - lastFetchTime < CACHE_DURATION
  ) {
    // Serve cached data if it's fresh
    return res.status(200).json(cachedTweets);
  }


  const access_token = process.env.TWITTER_ACCESS_TOKEN;

  const twitterUserId = 0000000000;
  const twitterEndpoint = `https://api.twitter.com/2/tweets?ids=${twitterUserId}&tweet.fields=created_at,text`;
  console.log(twitterEndpoint);
  try {
    const response = await axios.get(twitterEndpoint, {
      headers: {
        Authorization: `Bearer ${access_token}`,
      },
    });
    cachedTweets = response.data;
    lastFetchTime = Date.now();
    res.status(200).json(response.data);
  } catch (error) {
    res.status(500).json({ error: "Error fetching tweets" });
  }
}

useEffect(() => {
    const fetchTweets = async () => {
      try {
        const response = await axios.get("/api/tweets");
        setTweets(response.data.data.slice(0, 3)); 
        setLoadingTweets(false);
      } catch (error) {
        console.error("Error fetching tweets:", error);
        setLoadingTweets(false);
      }
    };

    fetchTweets();
  }, []);


I am tryiing to make it work seems like my endopoint is not working since it is giving page.tsx:57
GET http://localhost:3000/api/tweets 405 (Method Not Allowed)

0 Replies