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;
}
}
#error while add a cors to my next.js api
43 messages · Page 1 of 1 (latest)
🔎 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)
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 ?
or use middleware
what is better
middleware will works
with all api routes
request.headers.get('origin') its retrun to null
i don't know why
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
is this cuz i'm local host ?
it worked for me before
this is because the origin is only sent when u make a request from clientside to a different host
and u cant modify it on the clientside
i see so its not working cuz i'm at localhost
are u fetching from clientside?
to your own api?
yep
yeah its the same host
oh something else
it will only send origin when its not the same host
add authentication
by ip filter or how
nah thats not save
with jwe tokens or similar
or just for u?
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
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
✅ 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)
👍