discordjs in next js
Unanswered
XENOX posted this in #help-forum
XENOXOP
I can run discordjs in nodejs on replit but when I use the same code on nextjs it does not work.
It keeps throwing Can't resolve 'zlib-sync' which I think is node.js library
I tried this as a server action with "use server" but that was giving error on client side that can't import functions that use node
So I moved the code to api route and in route.ts file. but it's still not working.
My other API routes work fine,.
Below is the code
It keeps throwing Can't resolve 'zlib-sync' which I think is node.js library
I tried this as a server action with "use server" but that was giving error on client side that can't import functions that use node
So I moved the code to api route and in route.ts file. but it's still not working.
My other API routes work fine,.
Below is the code
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { Session } from "next-auth";
import authOptions from "@/lib/authOptions";
import { Client, GatewayIntentBits, EmbedBuilder } from "discord.js";
export async function POST(request: NextRequest) {
const session: Session | null = await getServerSession(authOptions);
if (!session) {
return NextResponse.json({
status: 404,
message: `Failed to fetch user, user not found`,
});
}
const body = await request.json();
console.log("Body", body);
const { discordChannel, buttonState, message } = body;
try {
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});
client.login(process.env.DISCORD_TOKEN);
const channel = await client.channels.fetch(discordChannel);
if (!channel) {
console.log("Could not connect to channel");
throw new Error(`Could not connect to channel: ${channel}`);
}
const formattedOffer = new EmbedBuilder()
.setColor("#0099ff") // Set the color of the embed
.setTitle(buttonState) // Set the title of the embed
.addFields({ name: "Issue", value: message, inline: true })
.setTimestamp();
await channel.send({ embeds: [formattedOffer] });
} catch (error: any) {
console.log("Failed to send feedback to discord", error);
throw new Error(`Failed to send feedback to discord: ${error.message}`);
}
}