{"record":{"id":"70ee9c02f927aef3","repo":"discordjs/discord.js","slug":"expected-token-to-be-set-for-this-request-but-non","errorCode":null,"errorMessage":"Expected token to be set for this request, but none was present","messagePattern":"Expected token to be set for this request, but none was present","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/rest/src/lib/REST.ts","lineNumber":322,"sourceCode":"\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\tif (typeof request.auth === 'object') {\n\t\t\t\theaders.Authorization = `${request.auth.prefix ?? this.options.authPrefix} ${request.auth.token}`;\n\t\t\t} else {\n\t\t\t\t// If we haven't received a token, throw an error\n\t\t\t\tif (!this.#token) {\n\t\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t\t}\n\n\t\t\t\theaders.Authorization = `${this.options.authPrefix} ${this.#token}`;\n\t\t\t}\n\t\t}\n\n\t\t// If a reason was set, set its appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record<string, string> = {};","sourceCodeStart":304,"sourceCodeEnd":340,"githubUrl":"https://github.com/discordjs/discord.js/blob/a81ed8a306d37fdc746e26a634b6a42164ba2c8c/packages/rest/src/lib/REST.ts#L304-L340","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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)."],"exampleFix":"// before\nconst rest = new REST();\nconst user = await rest.get(Routes.user('@me')); // Error: Expected token to be set...\n// after\nconst rest = new REST({ token: process.env.DISCORD_TOKEN });\nif (!rest.token) throw new Error('DISCORD_TOKEN is not set');\nconst user = await rest.get(Routes.user('@me'));","handlingStrategy":"validation","validationCode":"const token = process.env.DISCORD_TOKEN;\nif (!token) {\n  throw new Error('DISCORD_TOKEN environment variable is required but was not set');\n}\nconst rest = new REST({ token });","typeGuard":"const hasToken = (rest: REST): boolean => typeof rest.token === 'string' && rest.token.length > 0;\nif (!hasToken(rest)) rest.setToken(process.env.DISCORD_TOKEN!);","tryCatchPattern":"try {\n  data = await rest.get(Routes.user('@me'));\n} catch (error) {\n  if (error instanceof Error && error.message.includes('Expected token to be set')) {\n    rest.setToken(process.env.DISCORD_TOKEN!);\n    data = await rest.get(Routes.user('@me'));\n  } else {\n    throw error;\n  }\n}","preventionTips":["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."],"tags":["authentication","token","configuration","rest-client"],"backgroundTag":"missing-auth-token","analyzedSha":"a81ed8a306d37fdc746e26a634b6a42164ba2c8c","analyzedAt":"2026-08-30T04:07:22.193Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}