Next.js Discord

Discord Forum

error while add a cors to my next.js api

Answered
American black bear posted this in #help-forum
Open in Discord
American black bearOP
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import DiscordOauth2 from 'discord-oauth2';
import { authOptions } from '@/lib/auth';
const oauth = new DiscordOauth2();
import { api } from '@/lib/discordClient';
import cors, { runMiddleware } from '@/lib/cors';

export async function GET(req: NextRequest,res: NextResponse) {
  await runMiddleware(req, res, cors);
 
  try {
    const session = await getServerSession(authOptions as any) as any;

    if (!session || !session.accessToken) {
      return NextResponse.json({ message: 'No session or access token found' }, { status: 401 });
    }

    const allGuilds = await oauth.getUserGuilds(session.accessToken);

    const guilds = await Promise.all(
      allGuilds
      .filter(g => Number(g.permissions) & 8)
        .map(async (guild) => {
          const isJoined = await checkGuildMembership(guild.id, session.accessToken);
          return {
            ...guild,
            isJoined,
          };
        })
    );

    return NextResponse.json({ guilds });
  } catch (error: any) {
    return NextResponse.json({ message: 'Failed to fetch guilds', error: error.message }, { status: 500 });
  }
}

async function checkGuildMembership(guildId: string, accessToken: string): Promise<boolean> {
  try {
    const guild = await api.guilds.get(guildId) as any;

    if (!guild || guild.code === 10004) { 
      console.warn(`Guild not found or bot is not in the guild (guildId: ${guildId})`);
      return false;
    }

    return !!guild.id;
  } catch (error: any) {
    if (error.rawError?.code === 10004) {
      console.error(`Unknown Guild: ${guildId}`);
    } else {
      console.error(`Failed to check guild membership for guildId ${guildId}:`, error);
    }
    return false; 
  }
}
Answered by gin
this is because the origin is only sent when u make a request from clientside to a different host
View full answer

41 Replies

American black bearOP
import Cors from 'cors';

const cors = Cors({
  methods: ['GET', 'HEAD', 'POST'],  
  origin: '*', 
  allowedHeaders: ['Content-Type', 'Authorization'], 
});

function runMiddleware(req:any, res:any, fn:any) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result: any) => {
      if (result instanceof Error) {
        return reject(result);
      }
      return resolve(result);
    });
  });
}

export default cors;
export { runMiddleware };
⨯ TypeError: res.setHeader is not a function
is there way better ?
American black bearOP
what is better
middleware will works
with all api routes
request.headers.get('origin') its retrun to null
i don't know why
Double-striped Thick-knee
take a look ,
// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
    async headers() {
        return [
            {
                // matching all API routes
                source: "/api/:path*",
                headers: [
                    { key: "Access-Control-Allow-Credentials", value: "true" },
                    { key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin
                    { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
                    { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
                ]
            }
        ]
    }
}

module.exports = nextConfig
American black bearOP
is this cuz i'm local host ?
@American black bear what is better
depends on your usecase
i would set in middleware
@American black bear request.headers.get('origin') its retrun to null
this is because the origin is only sent when u make a request from clientside to a different host
Answer
and u cant modify it on the clientside
American black bearOP
i see so its not working cuz i'm at localhost
@American black bear i see so its not working cuz i'm at localhost
are u fetching from clientside?
to your own api?
@gin are u fetching from clientside?
American black bearOP
yep
yeah its the same host
American black bearOP
oh something else
it will only send origin when its not the same host
American black bearOP
what the best way to make my api not working for others
just for me
add authentication
@gin add authentication
American black bearOP
by ip filter or how
@American black bear by ip filter or how
nah thats not save
with jwe tokens or similar
or just for u?
@gin or just for u?
American black bearOP
no i mean someone try to see a some guild data
if its only for u u can just add a header with a password
@gin if its only for u u can just add a header with a password
American black bearOP
oh this good idea
u can also completely remove the clientside logic and fetch the api from server
or in this case u dont fetch api just use rsc
and fetch from discord directly
👍
have a nice day