Next.js Discord

Discord Forum

How can I make this faster? GET /api/mutual 304 in 7247ms

Answered
Schneider’s Smooth-fronted Caima… posted this in #help-forum
Open in Discord
Schneider’s Smooth-fronted CaimanOP
import React from "react";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import type { NextApiRequest, NextApiResponse } from "next";
import { createClient } from "redis";

const redisClient = createClient({
  url: process.env.REDIS_URL,
});

await redisClient.connect();

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await getServerSession(req, res, authOptions);

  if (!session) {
    return res.status(401).json({ message: "Unauthorized" });
  }

  const cacheKey = `discord:servers:${session.user.id}`;
  let guilds;

  try {
    const cachedGuilds = await redisClient.get(cacheKey);
    if (cachedGuilds) {
      guilds = JSON.parse(cachedGuilds);
    } else {
      const Discord = await fetch(`https://discord.com/api/users/@me/guilds`, {
        headers: {
          Authorization: `Bearer ${session.accessToken}`,
        },
      });
      guilds = await Discord.json();

      await redisClient.set(cacheKey, JSON.stringify(guilds), {
        EX: 3600,
      });
    }
  } catch (error) {
    console.error("Redis error:", error);
    return res.status(500).json({ message: "Internal Server Error" });
  }

  const Mutual = await fetch(`${process.env.API_URL}/mutual_servers?perm=admin`, {
    method: "POST",
    body: JSON.stringify({
      user: session.user.id,
      guilds: guilds.map((guild: any) => guild.id),
    }),
    headers: {
      "Content-Type": "application/json",
    },
  });
  const mutualGuilds = await Mutual.json();
  res.status(200).json({ mutualGuilds });
}
Answered by B33fb0n3
in dev mode the route also compiles and that can be slower than in production. Make sure you test things in production it should be way faster. For faster compile times in dev use --turbopack. The rest does not seem to be very influcenable, as you using the discord API and this shas it's own timings
View full answer

7 Replies

Schneider’s Smooth-fronted CaimanOP
I'm not great at nextjs at all
@Schneider’s Smooth-fronted Caiman import React from "react"; import { getServerSession } from "next-auth/next"; import { authOptions } from "@/pages/api/auth/[...nextauth]"; import type { NextApiRequest, NextApiResponse } from "next"; import { createClient } from "redis"; const redisClient = createClient({ url: process.env.REDIS_URL, }); await redisClient.connect(); export default async function handler( req: NextApiRequest, res: NextApiResponse ) { const session = await getServerSession(req, res, authOptions); if (!session) { return res.status(401).json({ message: "Unauthorized" }); } const cacheKey = `discord:servers:${session.user.id}`; let guilds; try { const cachedGuilds = await redisClient.get(cacheKey); if (cachedGuilds) { guilds = JSON.parse(cachedGuilds); } else { const Discord = await fetch(`https://discord.com/api/users/@me/guilds`, { headers: { Authorization: `Bearer ${session.accessToken}`, }, }); guilds = await Discord.json(); await redisClient.set(cacheKey, JSON.stringify(guilds), { EX: 3600, }); } } catch (error) { console.error("Redis error:", error); return res.status(500).json({ message: "Internal Server Error" }); } const Mutual = await fetch(`${process.env.API_URL}/mutual_servers?perm=admin`, { method: "POST", body: JSON.stringify({ user: session.user.id, guilds: guilds.map((guild: any) => guild.id), }), headers: { "Content-Type": "application/json", }, }); const mutualGuilds = await Mutual.json(); res.status(200).json({ mutualGuilds }); }
in dev mode the route also compiles and that can be slower than in production. Make sure you test things in production it should be way faster. For faster compile times in dev use --turbopack. The rest does not seem to be very influcenable, as you using the discord API and this shas it's own timings
Answer
@Schneider’s Smooth-fronted Caiman solved?
@B33fb0n3 <@795743076520820776> solved?
Schneider’s Smooth-fronted CaimanOP
mhm
@Schneider’s Smooth-fronted Caiman mhm
mhm, yes? Or mhm, no (what else do you need)?
@B33fb0n3 mhm, yes? Or mhm, no (what else do you need)?
Schneider’s Smooth-fronted CaimanOP
yes