mastra-ai/mastra · error · Error

Failed to get Netlify AI Gateway token: ${response.status} $

Error message

Failed to get Netlify AI Gateway token: ${response.status} ${error}

What it means

getOrFetchToken fetches a gateway token from the Netlify API using the NETLIFY_TOKEN bearer credentials. When the HTTP response is not ok, it throws a plain Error containing the HTTP status and response body text. This error is usually wrapped by NETLIFY_GATEWAY_TOKEN_ERROR (1391/1395) at call sites.

Source

Thrown at packages/core/src/llm/model/gateways/netlify.ts:125

    // Check cache first
    const cached = (await this.tokenCache.get(cacheKey)) as CachedToken | undefined;
    if (cached && cached.expiresAt > Date.now() / 1000 + 60) {
      // Return cached token if it won't expire in the next minute
      return { token: cached.token, url: cached.url };
    }

    // Fetch new token
    const response = await fetch(`https://api.netlify.com/api/v1/sites/${siteId}/ai-gateway/token`, {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${netlifyToken}`,
      },
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`Failed to get Netlify AI Gateway token: ${response.status} ${error}`);
    }

    const tokenResponse = (await response.json()) as NetlifyTokenResponse;

    // Cache the token - InMemoryServerCache will handle the TTL
    await this.tokenCache.set(cacheKey, {
      token: tokenResponse.token,
      url: tokenResponse.url,
      expiresAt: tokenResponse.expires_at,
    });

    return { token: tokenResponse.token, url: tokenResponse.url };
  }

  /**
   * Get cached token or fetch a new site-specific AI Gateway token from Netlify
   */
  async getApiKey(modelId: string): Promise<string> {

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Check the status code in the message: 401/403 → fix NETLIFY_TOKEN; 404 → fix NETLIFY_SITE_ID; 5xx → retry later
  2. Regenerate the Netlify personal access token and update the environment secret
  3. Validate the site ID against `netlify sites:list`
  4. Inspect the response body text in the message for Netlify's specific error detail
Defensive patterns

Strategy: retry

Validate before calling

// Pre-flight: verify token validity before use
const res = await fetch('https://api.netlify.com/api/v1/user', {
  headers: { Authorization: `Bearer ${process.env.NETLIFY_TOKEN}` },
});
if (!res.ok) throw new Error(`NETLIFY_TOKEN invalid: HTTP ${res.status}`);

Try / catch

try {
  const token = await gateway.getApiKey('netlify/openai/gpt-4o');
} catch (e) {
  const msg = e instanceof Error ? e.message : String(e);
  if (/status: (5\d\d|429)/.test(msg)) {
    // transient: retry with backoff
  } else if (/status: (401|403)/.test(msg)) {
    // credentials: fix NETLIFY_TOKEN, do not blind-retry
  }
  throw e;
}

Prevention

When it happens

Trigger: The Netlify token endpoint returns a non-2xx status — 401 for invalid/expired NETLIFY_TOKEN, 404 for a bad site ID, 5xx for Netlify-side issues — during getOrFetchToken.

Common situations: Rotated or revoked Netlify access token still deployed; token lacking permission for AI Gateway; site deleted or site ID typo; Netlify API incident.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/55e08628edddd076. Report an issue: GitHub.