How to use discord.js in Nextjs app dir

Hello, I am trying to use discord.js in my app but getting alot of errors, is this even possible?:
import { getServerAuthStatus } from "@/lib/session";
import { z } from "zod";
import { giveRole } from "./actions";

export default async function Home() {
const session = await getServerAuthStatus();
console.log(session);

async function handleSubmit(values: FormData) {
"use server";

const name = z.string().parse(values.get("name"));
if (name) {
console.log(name);
await giveRole(name);
}
}

return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex">
{JSON.stringify(session)}

<form action={handleSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
</div>
</main>
);
}
import { getServerAuthStatus } from "@/lib/session";
import { z } from "zod";
import { giveRole } from "./actions";

export default async function Home() {
const session = await getServerAuthStatus();
console.log(session);

async function handleSubmit(values: FormData) {
"use server";

const name = z.string().parse(values.get("name"));
if (name) {
console.log(name);
await giveRole(name);
}
}

return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex">
{JSON.stringify(session)}

<form action={handleSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
</div>
</main>
);
}
actions.ts
"use server";

import { Client, GatewayIntentBits } from "discord.js";
import { config } from "@/lib/config";

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on("ready", () => {
console.log(`Bot logged in!`);
});

client.login(config.DISCORD_BOT_TOKEN);

export const giveRole = async (name: string) => {
const user = client.users.cache.find(
(user) => user.username.toLowerCase() === name.toLowerCase()
);
const guild = client.guilds.cache.get(config.DISCORD_SERVER_ID);
const role = guild?.roles.cache.find(
(role) => role.id === config.DISCORD_ROLE_ID
);

if (user && guild && role) {
const member = guild.members.cache.get(user.id);
if (member) {
await member.roles.add(role);
}
}
};
"use server";

import { Client, GatewayIntentBits } from "discord.js";
import { config } from "@/lib/config";

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.on("ready", () => {
console.log(`Bot logged in!`);
});

client.login(config.DISCORD_BOT_TOKEN);

export const giveRole = async (name: string) => {
const user = client.users.cache.find(
(user) => user.username.toLowerCase() === name.toLowerCase()
);
const guild = client.guilds.cache.get(config.DISCORD_SERVER_ID);
const role = guild?.roles.cache.find(
(role) => role.id === config.DISCORD_ROLE_ID
);

if (user && guild && role) {
const member = guild.members.cache.get(user.id);
if (member) {
await member.roles.add(role);
}
}
};
R
rocawear321d ago
- event compiled client and server successfully in 1864 ms (306 modules)
- wait compiling...
- event compiled client and server successfully in 350 ms (306 modules)
- wait compiling /_error (client and server)...
- event compiled client and server successfully in 146 ms (311 modules)
- warn Fast Refresh had to perform a full reload due to a runtime error.
- wait compiling /page (client and server)...
- error ./node_modules/.pnpm/@discordjs+ws@0.8.3/node_modules/@discordjs/ws/dist/index.mjs:522:36
Module not found: Can't resolve 'zlib-sync'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx
- wait compiling...
- warn ./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/client/websocket/WebSocketManager.js
Module not found: Can't resolve 'zlib-sync' in 'D:\projektit\discord-role\node_modules\.pnpm\discord.js@14.11.0\node_modules\discord.js\src\client\websocket'

Import trace for requested module:
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/client/websocket/WebSocketManager.js
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx

./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/buffer-util.js
Module not found: Can't resolve 'bufferutil' in 'D:\projektit\discord-role\node_modules\.pnpm\ws@8.13.0\node_modules\ws\lib'

Import trace for requested module:
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/buffer-util.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/sender.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/wrapper.mjs
./node_modules/.pnpm/@discordjs+ws@0.8.3/node_modules/@discordjs/ws/dist/index.mjs
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx
- event compiled client and server successfully in 1864 ms (306 modules)
- wait compiling...
- event compiled client and server successfully in 350 ms (306 modules)
- wait compiling /_error (client and server)...
- event compiled client and server successfully in 146 ms (311 modules)
- warn Fast Refresh had to perform a full reload due to a runtime error.
- wait compiling /page (client and server)...
- error ./node_modules/.pnpm/@discordjs+ws@0.8.3/node_modules/@discordjs/ws/dist/index.mjs:522:36
Module not found: Can't resolve 'zlib-sync'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx
- wait compiling...
- warn ./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/client/websocket/WebSocketManager.js
Module not found: Can't resolve 'zlib-sync' in 'D:\projektit\discord-role\node_modules\.pnpm\discord.js@14.11.0\node_modules\discord.js\src\client\websocket'

Import trace for requested module:
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/client/websocket/WebSocketManager.js
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx

./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/buffer-util.js
Module not found: Can't resolve 'bufferutil' in 'D:\projektit\discord-role\node_modules\.pnpm\ws@8.13.0\node_modules\ws\lib'

Import trace for requested module:
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/buffer-util.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/sender.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/wrapper.mjs
./node_modules/.pnpm/@discordjs+ws@0.8.3/node_modules/@discordjs/ws/dist/index.mjs
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/validation.js
Module not found: Can't resolve 'utf-8-validate' in 'D:\projektit\discord-role\node_modules\.pnpm\ws@8.13.0\node_modules\ws\lib'

Import trace for requested module:
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/validation.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/sender.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/wrapper.mjs
./node_modules/.pnpm/@discordjs+ws@0.8.3/node_modules/@discordjs/ws/dist/index.mjs
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/validation.js
Module not found: Can't resolve 'utf-8-validate' in 'D:\projektit\discord-role\node_modules\.pnpm\ws@8.13.0\node_modules\ws\lib'

Import trace for requested module:
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/validation.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/lib/sender.js
./node_modules/.pnpm/ws@8.13.0/node_modules/ws/wrapper.mjs
./node_modules/.pnpm/@discordjs+ws@0.8.3/node_modules/@discordjs/ws/dist/index.mjs
./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/index.js
./src/app/actions.ts
./src/app/page.tsx
these are not found se everything that has this .node_modules/.pnpm does not work, so the hoisting(?) is not working correctly?
- warn ./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/client/websocket/WebSocketManar.js
Module not found: Can't resolve 'zlib-sync' in 'D:\projektit\discord-role\node_modules\.pnpm\discord.js@111.0\node_modules\discord.js\src\client\websocket'
- warn ./node_modules/.pnpm/discord.js@14.11.0/node_modules/discord.js/src/client/websocket/WebSocketManar.js
Module not found: Can't resolve 'zlib-sync' in 'D:\projektit\discord-role\node_modules\.pnpm\discord.js@111.0\node_modules\discord.js\src\client\websocket'
R
Rhys276d ago
@ruhap Did you end up finding a solution to this?
D
Desch276d ago
discord.JS needs a persistent server connection, so it isn’t really compatible with a website server architecture 😦 If you write an HTTP Interaction bot, that would fit into Next a little better
D
Desch276d ago
In this case, I’d recommend checking out this sub package: https://www.npmjs.com/package/@discordjs/rest
npm
@discordjs/rest
The REST API for discord.js. Latest version: 1.7.1, last published: 2 months ago. Start using @discordjs/rest in your project by running npm i @discordjs/rest. There are 228 other projects in the npm registry using @discordjs/rest.
D
Desch276d ago
Should be what you want!
R
Rhys276d ago
The main thing I'm wanting from Discord.js is the PermissionsBitfield so I don't have to implement that from scratch - do you know of any packages that provide just that? discord-api-types has the permission bits but doesn't provide a bitfield class to resolve a bitfield
D
Desch276d ago
i could add that to interaction kit pretty easily as a standalone package sometime next week
Want results from more Discord servers?
Add your server
More Posts
best way to fetch data in nextjsI was wondering what's the best way at the moment to query for external apis in NextJS? I know that @next/font turbo t3You might be using incompatible version of `@next/font` (13.4.4) and `next` (13.1.6). what version sTypescript issue causing trpc functions to not have type checkingHey, I'm in a create-t3-turbo app and have been banging my head against the wall trying to figure ouClerk middleware breaks Discord URL preview (embed)Anyone know how to fix this ...?T3 env lint error on Github CIRun npm run lint > chirp@0.1.0 lint > next lint ❌ Invalid environment variables: { PUSHER_APP_IDT3 Expo - react-native-gesture-handlerAnyone used this package with t3 turbo on expo app? I'm getting a package not found error on compileServer side caching with Next APIUnsure if this pattern is common, or if I am approaching this incorrectly. I am using an api in my [vite-plugin-sass] Unexpected token u in JSON at position 0 errorI just migrated my react sass application from webpack to Vite but I haven’t been able to build sincuseInfiniteQueryBug - queries to the end of pageI set up infinite scroll using the infinite query function in trpc. I have this bug right when the OpenId Connect ProviderHey Guys, im trying to implement a custom oidc auth provider, i've checked the Auth.js / NextAuth doruntimeEnv property in env.mjs in create-t3-appHey all, Was playing around entering some vars in the `.env` file and noticed that my app was builESLintrc.cjs config setupUnder Create T3 I setup ESLint in rules with: ``` rules: { '@typescript-eslint/no-unsafe-member-acce/app dir slower than pages?Hey, is the /app dir actually slower than the regular pages dir from next 12? If so, is it even a pVercel - SubdomainsHello hello, I wanted to ask whether there's a way for me to set-up two different projects (which arT3 Env Not Showing Type ErrorsHello, I have the following `env.mjs` file but there is no type error be shown in my IDE even thoughMy prisma var is any typeHello, i use the create t3 turbo repo and the prisma variable is any : ```ts import { PrismaClientTypeError: Cannot read properties of undefined (reading 'status')What am I doing wrong? Nextjs: `^13.2.4` Nodejs: `18.5.0`Stuck with a TS error for `Object.keys` 😞Hello all, got a pretty nasty issue that I need to fix otherwise I will not be able to move on with SSR with NextJs layouts (page dir)So I have a shared layout in my app which looks like this ```js const Page: NextPageWithLayout = () "it works on my machine" deployed app to vercel and it blew upit was hard enough to build the app, I overcame the chanllenges and tried to deploy the first versio