discordjs/discord.js · error · Error
Expected token to be set for this request, but none was pres
Error message
Expected token to be set for this request, but none was present
What it means
In resolveRequest(), when a request requires authentication (request.auth is not false and not an object with an explicit token) and no token was configured on the REST instance (this.#token is undefined), this Error is thrown. The library refuses to send an unauthenticated request that the API contract says must be authorized.
Source
Thrown at packages/rest/src/lib/REST.ts:322
if (resolvedQuery !== '') {
query = `?${resolvedQuery}`;
}
}
// Create the required headers
const headers: RequestHeaders = {
...this.options.headers,
'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),
};
// If this request requires authorization (allowing non-"authorized" requests for webhooks)
if (request.auth !== false) {
if (typeof request.auth === 'object') {
headers.Authorization = `${request.auth.prefix ?? this.options.authPrefix} ${request.auth.token}`;
} else {
// If we haven't received a token, throw an error
if (!this.#token) {
throw new Error('Expected token to be set for this request, but none was present');
}
headers.Authorization = `${this.options.authPrefix} ${this.#token}`;
}
}
// If a reason was set, set its appropriate header
if (request.reason?.length) {
headers['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);
}
// Format the full request URL (api base, optional version, endpoint, optional querystring)
const url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${
request.fullRoute
}${query}`;
let finalBody: RequestInit['body'];
let additionalHeaders: Record<string, string> = {};View on GitHub (pinned to a81ed8a306)
Solutions
- Pass the token at construction: new REST({ token: process.env.DISCORD_TOKEN }).
- Call rest.setToken(token) before making requests if the token is obtained later (e.g. after login).
- Verify the env variable is actually defined at startup and fail fast with a clear message if it isn't.
- If the request genuinely shouldn't be authenticated, pass { auth: false } in the request options (only valid for routes that allow anonymous access).
Example fix
// before
const rest = new REST();
const user = await rest.get(Routes.user('@me')); // Error: Expected token to be set...
// after
const rest = new REST({ token: process.env.DISCORD_TOKEN });
if (!rest.token) throw new Error('DISCORD_TOKEN is not set');
const user = await rest.get(Routes.user('@me')); Defensive patterns
Strategy: validation
Validate before calling
const token = process.env.DISCORD_TOKEN;
if (!token) {
throw new Error('DISCORD_TOKEN environment variable is required but was not set');
}
const rest = new REST({ token }); Type guard
const hasToken = (rest: REST): boolean => typeof rest.token === 'string' && rest.token.length > 0; if (!hasToken(rest)) rest.setToken(process.env.DISCORD_TOKEN!);
Try / catch
try {
data = await rest.get(Routes.user('@me'));
} catch (error) {
if (error instanceof Error && error.message.includes('Expected token to be set')) {
rest.setToken(process.env.DISCORD_TOKEN!);
data = await rest.get(Routes.user('@me'));
} else {
throw error;
}
} Prevention
- Load dotenv (or your secrets manager) before constructing REST and assert the token exists at startup.
- Always pass `token` in the REST constructor rather than relying on a later setToken() call.
- For anonymous-only routes, explicitly pass { auth: false } in request options so intent is clear.
- Never assign the token from a possibly-undefined env var without a null check.
When it happens
Trigger: Calling `rest.get('/users/@me')` (or any auth-required route) without passing `token` in `new REST({ token })` and without calling `rest.setToken(...)`; the token being undefined because an environment variable was empty (process.env.DISCORD_TOKEN undefined); passing `auth: true` explicitly (or relying on the default) on a REST instance constructed with no token.
Common situations: Missing or misnamed env var (DISCORD_TOKEN not loaded because dotenv wasn't initialized); deploying without the token secret configured; creating a REST instance in a library/util module and forgetting setToken(); a revoked/regenerated bot token that code cleared to undefined.
Related errors
- Token has not been set
- Cannot set an interval greater than 4 hours
- Token has already been set
- Encountered HTTP 401 with error ${data.code}: ${data.message
- Package ${packageName} not releaseable
AI-assisted analysis of discordjs/discord.js@a81ed8a306 (2026-08-30).
Data as JSON: /api/errors/70ee9c02f927aef3.
Report an issue: GitHub.