Next.js Discord

Discord Forum

Fetching data

Answered
Shaurya posted this in #help-forum
Open in Discord
Avatar
export function Stats() {
  const [totalGuilds, setTotalGuilds] = useState("N/A")

  useEffect(() => {
    async function getGuilds() {
      const guilds = await getTotalGuilds()
      setTotalGuilds(guilds)
    }

    getGuilds()
  }, [])

  return (
    <div className={styles.stats}>
      {totalGuilds}
    </div>
  )
}
export async function getTotalGuilds() {
  const token = process.env.NEXT_PUBLIC_BOT_TOKEN

  if (!token) return "N/A"

  const guildsEndpoint = `${dapi}/users/@me/guilds`

  const response = await fetch(guildsEndpoint, {
    headers: {
      Authorization: `Bot ${token}`
    }
  })

  const guilds = await response.json() as Guild[] | undefined
  const totalGuilds = guilds ? guilds.length.toString() : "N/A"

  return totalGuilds
}
This works okay but I get the error
GET https://discord.com/api/v10/users/@me/guilds 429 (Too Many Requests)
but I'm fetching only once? how is it repeating?
Answered by joulev
server component, or [route handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), or your separate backend, etc basically anywhere that is not in the browser
View full answer

9 Replies

Avatar
idk what's the answer to your question, but bot tokens are secrets so do not expose them to the browser by using NEXT_PUBLIC
instead make authenticated server-side api routes instead, and use the bot token there
and fetch that api route from your frontend
Avatar
oh, yeah
do you mean making it a server component?
can you link me the docs please if that's not what you meant
Avatar
server component, or [route handler](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), or your separate backend, etc basically anywhere that is not in the browser
Answer
Avatar
thanks,
export default async function Stats() {
  const data = await getTotalGuilds()

  return (
    <div className={styles.stats}>
      {data}
    </div>
  )
}
export async function getTotalGuilds() {
  const token = process.env.BOT_TOKEN

  if (!token) return "N/A"

  const response = await fetch(`${dapi}/users/@me/guilds`, {
    headers: {
      Authorization: `Bot ${token}`
    }
  })

  const guilds = await response.json() as Guild[] | undefined
  const totalGuilds = Array.isArray(guilds) ? guilds.length.toString() : "N/A"

  return totalGuilds
}
it's working good rn, not getting the too many requests error
this one is safe right? got rid of the NEXT_PUBLIC
Avatar
yes that is safe