discord.js
Discord.js is a comprehensive, performant, and object-oriented JavaScript library designed for interacting with the Discord API. It simplifies bot development by abstracting complex API calls and WebSocket management, providing a rich set of classes and utilities. The current stable version is 14.26.3, and the library maintains a frequent release cadence, often pushing out minor bug fixes and new features to keep pace with Discord's evolving API, as evidenced by the rapid 14.26.x updates. Key differentiators include its extensive documentation, a large and active community, and a modular ecosystem (e.g., `@discordjs/rest`, `@discordjs/builders`, `@discordjs/voice`) that allows developers to integrate specific functionalities as needed. It supports both CommonJS and ES Modules, with modern usage heavily favoring ESM and TypeScript for type safety and modern JavaScript features.
Common errors
-
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
cause The bot's client was instantiated without specifying required Gateway Intents in its configuration.fixProvide an array of `GatewayIntentBits` to the `intents` property in the `Client` constructor. Remember to also enable privileged intents in the Discord Developer Portal if needed. -
Error [TOKEN_INVALID]: An invalid token was provided.
cause The bot token provided in `client.login()` is incorrect, expired, regenerated, or revoked.fixVerify the bot token in your code matches the token from the Discord Developer Portal. Regenerate the token on the portal if unsure, and ensure it's kept private. -
ReferenceError: Intents is not defined
cause In discord.js v14, `Intents.FLAGS` was replaced by `GatewayIntentBits`. Old code trying to access `Intents.FLAGS` will throw this error.fixReplace `Intents.FLAGS.<INTENT_NAME>` with `GatewayIntentBits.<IntentName>` and ensure `GatewayIntentBits` is imported from `discord.js`. -
ReferenceError: require is not defined in ES module scope, you can use import instead
cause Attempting to use `require()` in a JavaScript file that is being treated as an ES Module (e.g., due to `"type": "module"` in `package.json`).fixChange your import statements from `const Discord = require('discord.js');` to `import * as Discord from 'discord.js';` or `import { Client } from 'discord.js';`. Alternatively, ensure your `package.json` does not have `"type": "module"` if you intend to use CommonJS.
Warnings
- breaking Discord.js v14 removed Node.js versions older than 16.9.0, now requiring Node.js 18.0.0 or newer (the official documentation for 14.26.2 specifies Node.js 22.12.0 or newer). This can break deployments on older Node.js environments.
- breaking Gateway Intents became mandatory in discord.js v13 and were further refined in v14. Bots must explicitly declare which event categories they intend to receive from Discord. Failing to provide intents or enabling privileged intents without Discord Developer Portal approval will prevent the bot from logging in or receiving events.
- breaking Several core event names were changed in v14 for better clarity and consistency. For example, `client.on('message', ...)` became `client.on(Events.MessageCreate, ...)` and `client.on('interaction', ...)` became `client.on(Events.InteractionCreate, ...)`.
- breaking Discord.js v14 introduced breaking changes to the REST API internals, including the use of global `fetch` which requires Node.js v18+. The `REST` module's `raw` method now returns a web-compatible `Response` object, and `parseResponse` operates on this new object.
- gotcha Partials, which allow the bot to handle events from uncached data, are now explicit. If your bot needs to react to events from old messages, channels, or users that might not be in its cache, you must enable the relevant `Partials` in the `Client` constructor. Failure to do so will result in events not firing for uncached data.
- gotcha When running Node.js with `"type": "module"` in `package.json`, attempting to use `require()` for discord.js or other ESM-only modules will result in a `ReferenceError: require is not defined in ES module scope` error.
Install
-
npm install discord.js -
yarn add discord.js -
pnpm add discord.js
Imports
- Client
const Discord = require('discord.js'); const client = new Discord.Client();import { Client, Events, GatewayIntentBits } from 'discord.js'; - GatewayIntentBits
import { Intents } from 'discord.js'; // Deprecated in v14; previously Intents.FLAGS.GUILDS. const client = new Client({ intents: [Intents.FLAGS.GUILDS] });import { GatewayIntentBits } from 'discord.js'; - Events
client.on('message', ...); // Deprecated event name. client.on('interaction', ...); // Deprecated event name.import { Events } from 'discord.js'; - Partials
const client = new Client({ partials: ['MESSAGE', 'CHANNEL'] });import { Partials } from 'discord.js';
Quickstart
import { Client, Events, GatewayIntentBits } from 'discord.js';
// Create a new client instance with required intents and partials
// Intents are crucial for specifying which events your bot wants to receive from Discord.
// MessageContent is a privileged intent and must be enabled in the Discord Developer Portal.
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent // Required for reading message content in v14+
],
partials: [
Partials.Message,
Partials.Channel,
Partials.Reaction // Example partials, enable as needed
]
});
// When the client is ready, run this once.
// The 'ready' event indicates that the bot has successfully logged in.
client.once(Events.ClientReady, readyClient => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
// Listen for 'messageCreate' events to respond to messages
client.on(Events.MessageCreate, async message => {
// Ignore messages from other bots or messages without content
if (message.author.bot || !message.content) return;
if (message.content.toLowerCase() === 'ping') {
await message.reply('Pong!');
}
if (message.content.toLowerCase() === 'hello') {
await message.channel.send(`Hello, ${message.author.username}!`);
}
});
// Log in to Discord with your client's token
// Make sure to set your bot token in an environment variable named DISCORD_TOKEN
// or provide it directly (not recommended for production).
client.login(process.env.DISCORD_TOKEN ?? '').catch(console.error);