DiscordKit uses the DiscordSession class to manage authentication and API communication with Discord. The session handles token management, rate limiting, and request queueing automatically.
The simplest way to authenticate is to set your token when your application starts:
import { discord } from '@discordkit/client';// Option 1: Set token during initializationconst session = new DiscordSession(`Bot ${process.env.BOT_TOKEN}`);// Option 2: Set token on the default instancediscord.setToken(`Bot ${process.env.BOT_TOKEN}`);
The setToken method validates your token format and throws an error if invalid:
import { discord } from '@discordkit/client';try { discord.setToken(`Bot ${process.env.BOT_TOKEN}`); console.log('Token set successfully');} catch (error) { // Error: Token must begin with either "Bot " or "Bearer " console.error('Invalid token format:', error);}
Never hardcode tokens in your source code. Always use environment variables or secure secret management.
import { discord } from '@discordkit/client';try { const token = discord.getSession(); // Use token...} catch (error) { // Error: Auth Token must be set before requests can be made. console.error('No token set:', error);}
The DiscordSession automatically handles Discord’s rate limits:
Global Rate Limit: 50 requests per second
Per-Route Rate Limits: Managed via bucket headers
Invalid Request Tracking: 10,000 per 10 minutes
All requests are automatically queued and throttled to stay within these limits.Source: /home/daytona/workspace/source/packages/core/src/requests/DiscordSession.ts:38
import { discord, getCurrentApplication } from '@discordkit/client';// ❌ Wrong - token not setconst app = await getCurrentApplication();// Error: Auth Token must be set before requests can be made.// ✅ Correctdiscord.setToken(`Bot ${process.env.BOT_TOKEN}`);const app = await getCurrentApplication();