AI Copilot

when I try to use my AI Copilot in my payroll processing app, an AI credit is taken off my balance, but I immediate;y get the error message ‘unauthorised’. I have checked all of the relevant environment variables to no avail

Hi Adam,

I’d separate “the environment variable exists” from “the request is actually sending the right auth to the right place.”

If this is using Vercel AI Gateway, the request should be server-side and should send the Gateway key as a bearer token to the Gateway endpoint, not expose it in the browser:

const response = await fetch("https://ai-gateway.vercel.sh/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AI_GATEWAY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "openai/gpt-4.1-mini",
    messages: [{ role: "user", content: "test" }],
  }),
})

I’d also add a temporary server-side check that only logs whether the variable is present, not the value:

console.log("AI_GATEWAY_API_KEY present:", Boolean(process.env.AI_GATEWAY_API_KEY))

Then redeploy after confirming the variable exists in the same Vercel environment you’re testing, usually Production vs Preview.

If the credit is being deducted but your app shows “unauthorised,” also check whether that message is coming from your own payroll app auth/session layer rather than from the AI provider. The quickest way to tell is to log the actual HTTP status and response body from the AI request, with secrets removed.

Can you share the exact status code and redacted error body from the failed AI request?