bot-tutorial

Discord.js v14 Tutorial: Slash Commands & Event Handlers

A step-by-step Discord.js v14 tutorial covering slash command registration, modular event handlers, and best practices for modern bot development.

November 9, 2026 · 1134 views

If you're building a bot with Discord.js v14, you’re stepping into the most robust, stable, and officially supported version of the library — and it’s all about slash commands and clean architecture. Gone are the days of messageCreate-only bots; v14 embraces Discord’s modern interaction model with native support for application commands, buttons, modals, and proper event-driven design. In this comprehensive Discord.js v14 tutorial, we’ll walk through setting up slash commands (global and guild-specific), implementing a scalable event handler, and organizing your code like a pro 🚀. Whether you're upgrading from v13 or starting fresh, this guide gives you production-ready patterns — not just quick hacks.

Why Discord.js v14 Is a Game-Changer

Discord.js v14 (released in late 2023 and actively maintained through 2026) is built on top of Discord’s HTTP v10 API and fully supports slash commands, context menus, autocompletes, modals, and interaction responses — all without workarounds. Unlike v13, which required manual REST calls or third-party wrappers for command registration, v14 includes REST, Routes, and first-class ApplicationCommandManager utilities out of the box.

More importantly, v14 encourages separation of concerns: events live in dedicated files, commands are modular and reusable, and error handling is centralized. That means less spaghetti code and faster iteration — especially as your Discord server grows beyond 100 members.

💡 Pro tip: Discord.js v14 drops Node.js <16.9 support — make sure you're running Node.js 18.17+ or 20.x for full compatibility and security patches.

Prerequisites & Project Setup

Before writing any code, ensure you have:

  • A Discord Developer Portal application ✅
  • Your bot token and client ID handy 🔑
  • Node.js v18.17+ installed (node -v to verify)
  • A code editor (VS Code recommended)
  • Basic JavaScript/TypeScript knowledge

Initialize your project:

mkdir my-discord-bot
cd my-discord-bot
npm init -y
npm install discord.js @discordjs/rest discord-api-types
npm install -D typescript ts-node @types/node

Then set up tsconfig.json (or use JavaScript if preferred — but TypeScript is strongly recommended for v14’s type safety). You’ll also want a .env file for secrets:

TOKEN=your_bot_token_here
CLIENT_ID=123456789012345678
GUILD_ID=987654321098765432 # optional — for guild-specific commands

Step-by-Step: Registering Slash Commands

Slash commands must be registered once via Discord’s REST API — either globally (available in all servers your bot joins) or per-guild (faster to deploy/test). We’ll show both approaches.

1. Define Your Commands

Create commands/ping.ts:

import { SlashCommandBuilder } from 'discord.js';

export default {
  data: new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Replies with Pong! 🏓'),
  async execute(interaction) {
    await interaction.reply('Pong!');
  },
};

And commands/echo.ts:

import { SlashCommandBuilder } from 'discord.js';

export default {
  data: new SlashCommandBuilder()
    .setName('echo')
    .setDescription('Repeats your message')
    .addStringOption(option =>
      option.setName('text')
        .setDescription('The text to echo')
        .setRequired(true)
    ),
  async execute(interaction) {
    const text = interaction.options.getString('text', true);
    await interaction.reply(`Echo: ${text}`);
  },
};

💡 Notice how .setRequired(true) enforces input — no more manual if (!text) checks!

2. Auto-Load Commands

Create deploy-commands.ts to collect and register all commands:

import { REST, Routes } from '@discordjs/rest';
import { Client, Collection, GatewayIntentBits } from 'discord.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const commands = [];
const commandFiles = fs.readdirSync(path.join(__dirname, 'commands')).filter(file => file.endsWith('.ts'));

for (const file of commandFiles) {
  const command = await import(`./commands/${file}`);
  commands.push(command.default.data.toJSON());
}

const rest = new REST({ version: '10' }).setToken(process.env.TOKEN!);

(async () => {
  try {
    console.log(`Started refreshing ${commands.length} application (/) commands.`);

    // ⚙️ For GLOBAL commands (takes 1hr to propagate)
    await rest.put(
      Routes.applicationCommands(process.env.CLIENT_ID!),
      { body: commands }
    );

    // 🧪 For GUILD commands (instant, great for testing)
    // await rest.put(
    //   Routes.applicationGuildCommands(process.env.CLIENT_ID!, process.env.GUILD_ID!),
    //   { body: commands }
    // );

    console.log('Successfully reloaded application commands.');
  } catch (error) {
    console.error(error);
  }
})();

Run with: npx ts-node deploy-commands.ts

✅ Done! Your /ping and /echo commands now appear in Discord.

[Image: Screenshot of Discord showing /ping and /echo in autocomplete]

Building a Modular Event Handler

Hardcoding client.on('ready', ...) and client.on('interactionCreate', ...) in your main file leads to clutter and poor maintainability. Let’s build a scalable event system.

Folder Structure

src/
├── events/
│   ├── clientReady.ts
│   ├── interactionCreate.ts
│   └── guildMemberAdd.ts
├── commands/
│   ├── ping.ts
│   └── echo.ts
├── index.ts          ← entry point
├── deploy-commands.ts
└── config.ts

1. Create an Event Loader

In index.ts:

import { Client, Collection, GatewayIntentBits } from 'discord.js';
import { readdirSync } from 'fs';
import { join } from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMembers,
  ],
});

client.commands = new Collection();

// Load events
const eventFiles = readdirSync(join(__dirname, 'events')).filter(file => file.endsWith('.ts'));

for (const file of eventFiles) {
  const event = await import(`./events/${file}`);
  if (event.once) {
    client.once(event.name, (...args) => event.execute(...args));
  } else {
    client.on(event.name, (...args) => event.execute(...args));
  }
}

// Login
client.login(process.env.TOKEN);

2. Example Event: interactionCreate.ts

import { Events, Interaction } from 'discord.js';

export const name = Events.InteractionCreate;
export const once = false;

export async function execute(interaction: Interaction) {
  if (!interaction.isChatInputCommand()) return;

  const command = interaction.client.commands.get(interaction.commandName);
  if (!command) {
    console.warn(`No command matching ${interaction.commandName} was found.`);
    return;
  }

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({
      content: 'There was an error while executing this command!',
      ephemeral: true,
    });
  }
}

This keeps logic decoupled and testable — and makes adding new events as simple as dropping a new file in /events.

Quick Tips for Real-World Stability

  • ✅ Always use ephemeral: true for error replies — avoids spamming channels with “bot failed” messages.
  • ✅ Validate options before execution: Use .getXXX() with true flag (e.g., getString('name', true)) to let Discord.js throw early.
  • ✅ Rate-limit awareness: Global commands update slowly — use guild commands during dev. Switch to global only after final QA.
  • ✅ Log interactions: Add console.log(${interaction.user.tag} used /${interaction.commandName}) in interactionCreate.ts for quick debugging.
  • ✅ Use DiscordCraft for battle-tested boilerplates, command scaffolding, and deployment scripts — it saves hours when scaling beyond 5–10 commands 🛠️

Pro Tips: Going Beyond Basics

  • Autocomplete support? Add .setAutocomplete(true) to your string/number option, then listen for AutocompleteInteraction in a dedicated event.
  • Subcommands & groups? Use addSubcommandGroup() and addSubcommand() — perfect for /music play, /music pause, etc.
  • Permissions? Set defaultMemberPermissions and dmPermission: false directly in the SlashCommandBuilder.
  • Localization? v14 supports setDescriptionLocalizations() and setNameLocalizations() — ideal for international Discord servers 🌍
  • TypeScript enums for constants? Define PermissionFlagsBits or ChannelType imports explicitly to avoid runtime surprises.

FAQ

Q: Do I need to re-deploy commands every time I add a new one?
A: Yes — but only once per change. Automate it with npm run deploy or integrate into your CI/CD (e.g., GitHub Actions on main push).

Q: Why does my slash command show but do nothing?
A: Most likely: (1) You forgot to handle interactionCreate, (2) The command isn’t loaded into client.commands, or (3) There’s a typo in the command name vs. execute() lookup.

Q: Can I use buttons or modals with this setup?
A: Absolutely! Buttons and modals are handled via interactionCreate too — just check interaction.isButton() or interaction.isModalSubmit() and route accordingly.

Final Thoughts & Next Steps

You’ve now built a foundation that scales: modular slash commands, a dynamic event loader, and idiomatic Discord.js v14 patterns. From here, you can confidently add features like database integration (e.g., @prisma/client), cooldown systems, permission guards, or even a web dashboard using Express + Discord OAuth2.

Remember: Great bots aren’t built in a day — they’re iterated, tested, and refined alongside your community. 🌟

Need inspiration or a head start? Check out DiscordCraft — it offers open-source templates, CLI generators (dc create:command), and deep-dive guides for advanced workflows like sharding, slash command permissions sync, and audit logging. All updated for Discord.js v14 and current Discord API behavior as of November 2026.

Happy coding — and may your interactions always be deferred 🫶 and your promises never rejected! 🐾