#error while add a cors to my next.js api

43 messages · Page 1 of 1 (latest)

wide mango
#
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; 
  }
}

errant cobaltBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

wide mango
#
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 ?

obsidian frigate
#

or use middleware

wide mango
#

what is better

#

middleware will works

#

with all api routes

#

request.headers.get('origin') its retrun to null

#

i don't know why

blazing plover
#

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
wide mango
#

is this cuz i'm local host ?

obsidian frigate
#

i would set in middleware

obsidian frigate
#

and u cant modify it on the clientside

wide mango
#

i see so its not working cuz i'm at localhost

obsidian frigate
#

to your own api?

wide mango
obsidian frigate
#

yeah its the same host

wide mango
#

oh something else

obsidian frigate
#

it will only send origin when its not the same host

wide mango
#

what the best way to make my api not working for others

#

just for me

obsidian frigate
#

add authentication

wide mango
obsidian frigate
#

with jwe tokens or similar

#

or just for u?

wide mango
obsidian frigate
#

if its only for u u can just add a header with a password

wide mango
obsidian frigate
#

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

errant cobaltBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1286690217398505532 message)

obsidian frigate
#

👍