santifer/career-ops · critical · Error

NOTION_ACCESS_TOKEN is not set (.env) — the Notion plugin…

Error message

NOTION_ACCESS_TOKEN is not set (.env) — the Notion plugin needs it to read/write.

What it means

createNotionClient() builds a minimal Notion REST client around an injected fetch function. The token is the single required config field: without a Bearer token every Notion API call would fail with 401 anyway, so the factory throws immediately with a message pointing at NOTION_ACCESS_TOKEN in .env. The function itself never reads process.env — the plugin layer is responsible for loading .env and passing the token in the cfg object.

Solutions

  1. Create/edit .env in the project root and add NOTION_ACCESS_TOKEN=secret_... from a Notion internal integration (notion.so/my-integrations).
  2. Verify the .env file is actually loaded before plugin init (e.g. dotenv/config or the engine's env loader runs first) and that the value reaches createNotionClient as cfg.token.
  3. Share the target Notion pages/databases with the integration in Notion (Connections menu) — a valid token without a shared parent will fail later in resolveDBs.
  4. If the token comes from CI secrets, confirm the secret name matches NOTION_ACCESS_TOKEN exactly and is scoped to the job.

Example fix

// before
const client = createNotionClient({ parent: process.env.NOTION_PARENT_PAGE_ID });

// after (.env)
# NOTION_ACCESS_TOKEN=secret_xxxxxxxxxxxx

// code
const token = process.env.NOTION_ACCESS_TOKEN;
if (!token) throw new Error('Set NOTION_ACCESS_TOKEN in .env before using the Notion plugin');
const client = createNotionClient({ token, parent: process.env.NOTION_PARENT_PAGE_ID });
Defensive patterns

Strategy: validation

Validate before calling

// before creating the client
if (!process.env.NOTION_ACCESS_TOKEN) {
  throw new Error('NOTION_ACCESS_TOKEN missing: add it to .env (Notion internal integration token)');
}

Type guard

function hasNotionToken(env = process.env): env is typeof env & { NOTION_ACCESS_TOKEN: string } {
  return typeof env.NOTION_ACCESS_TOKEN === 'string' && env.NOTION_ACCESS_TOKEN.startsWith('secret_');
}

Try / catch

let client;
try {
  client = createNotionClient({ token: process.env.NOTION_ACCESS_TOKEN, parent: process.env.NOTION_PARENT_PAGE_ID });
} catch (e) {
  if (/NOTION_ACCESS_TOKEN is not set/.test(e.message)) {
    console.error('Setup incomplete: copy .env.example to .env and fill in NOTION_ACCESS_TOKEN');
    process.exit(1);
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling createNotionClient({ parent }) or createNotionClient({ token: undefined }) when NOTION_ACCESS_TOKEN is absent from the environment/.env, the .env file was not loaded before the plugin initialized, or the config object key is misspelled ({ Token } or { authToken }) so destructuring yields undefined.

Common situations: Fresh clone where .env was never created from .env.example; an integration token revoked/deleted in Notion and removed from .env; CI environment where secrets are injected under a different name than the plugin expects; a rename refactor that changed the cfg key but not the call site.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of santifer/career-ops@aac998c7ed (2026-09-16). Data as JSON: /api/errors/48bf0f7f469dca0e. Report an issue: GitHub.

Appendix: source

Thrown at plugins/notion/_notion.mjs:67

  const str = String(text ?? '');
  const out = [];
  for (let i = 0; i < str.length || out.length === 0; i += MAX) out.push({ type: 'text', text: { content: str.slice(i, i + MAX) } });
  return out;
}

export function plain(prop) {
  return (prop?.title || prop?.rich_text || []).map((t) => t.plain_text).join('');
}

/**
 * Build a Notion client bound to one user's token + parent page. Network goes
 * through the injected `fetchFn` (the plugin passes ctx.fetch so the engine's
 * allowedHosts/HTTPS/redirect guard applies); falls back to global fetch for
 * standalone use. Nothing here reads process.env.
 * @param {{ token: string, parent: string, fetch?: Function }} cfg
 */
export function createNotionClient({ token, parent, fetch: fetchFn = globalThis.fetch }) {
  if (!token) throw new Error('NOTION_ACCESS_TOKEN is not set (.env) — the Notion plugin needs it to read/write.');
  const HEADERS = { Authorization: `Bearer ${token}`, 'Notion-Version': '2025-09-03', 'Content-Type': 'application/json' };
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

  async function api(path, method, body) {
    await sleep(360); // ~3 req/s
    // ctx.fetch throws on non-2xx (its message carries the body); the !r.ok
    // branch below is the fallback when a plain global fetch is injected.
    const r = await fetchFn(`https://api.notion.com/v1/${path}`, { method, headers: HEADERS, body: body ? JSON.stringify(body) : undefined });
    const j = await r.json();
    if (!r.ok) throw new Error(`Notion ${method} ${path} -> ${j.code}: ${j.message}`);
    return j;
  }

  /** Create a page in a data source. `markdown` (optional) becomes the page body. */
  async function createPage(dataSourceId, properties, markdown) {
    const body = { parent: { type: 'data_source_id', data_source_id: dataSourceId }, properties };
    if (markdown) body.markdown = markdown;
    return api('pages', 'POST', body);

View on GitHub (pinned to aac998c7ed)