Hugging Face token setup: fine-grained scopes, the router URL and why calls return 402
Create a fine-grained Hugging Face token with only the Inference Providers permission, store it as HF_TOKEN, call the router from your server and buy credits first.
The short version
Sign in at huggingface.co, open Settings, Access Tokens at huggingface.co/settings/tokens, choose New token, pick the fine-grained type and tick only Make calls to Inference Providers. Copy the value, which starts with hf_, into your host as HF_TOKEN, and call https://router.huggingface.co/v1 from server code. That endpoint speaks the OpenAI chat completions format, so the openai package works once you change the base URL. Before the first test, add credits under Billing: a free account has no monthly inference credits, so requests fail until you buy some or upgrade.
One Hugging Face token reaches many open models served by many companies, and Hugging Face says it passes the provider's price through with no markup. That makes it a good fit when you want open-weight models such as DeepSeek, Qwen or Llama without opening an account at each host. If you mainly want Claude, GPT or Gemini, a direct key from that lab, or an OpenRouter key, is the simpler choice.
Which token type to choose
Hugging Face offers three roles. The page that matters is what each one can reach if it leaks, because an app token sits on a server where logs, build output and teammates can all see the environment.
| Role | What it can do | Use it for |
|---|---|---|
| Fine-grained | Only the permissions and repositories you tick | Production apps. Hugging Face recommends only this type there |
| Read | Read every repository you can read, including private ones, and run inference | A personal laptop or notebook |
| Write | Everything read can do, plus push to any repository you can write to | Training jobs that upload models, never a web app |
Create the token, step by step
Then prove it works from your own terminal. A JSON reply with text in choices[0].message.content means the token, the permission and the billing are all right. A 401 means the variable does not hold the whole token or it was deleted; a 403 usually means the permission box was not ticked.
- Open huggingface.co/settings/tokens and choose New token.
- Choose Fine-grained. Since July 2026 the form offers presets (Read-Only, Inference, Write, CI/CD and Full Access); Inference is the closest, but check the summary and untick anything beyond Make calls to Inference Providers.
- Name it after the app and the environment, for example
myapp-prod, so you can delete this one token later without touching the others. - Copy the value straight into your host's environment variables as
HF_TOKEN. Hugging Face shows it again under Manage, but the safest copy is the one already on the server. - Open Settings, Billing, add a card and buy credits. Hugging Face suggests turning on automatic recharge so a busy day does not stop your app.
curl https://router.huggingface.co/v1/chat/completions \
-H "Authorization: Bearer $HF_TOKEN" \
-H "Content-Type: application/json" \
-d '{"model": "deepseek-ai/DeepSeek-V4.1-Flash:cheapest", "messages": [{"role": "user", "content": "Say hello"}]}'Why a working token still returns 402
The error people meet most reads "You have exceeded your monthly included credits for Inference Providers." It is about money, not the token. Hugging Face's pricing table explains why it appears so early:
| Account | Inference credits each month | Can keep going after that |
|---|---|---|
| Free | None | Yes, after you buy credits |
| PRO ($9 a month) | $2.00 | Yes, pay as you go |
| Team or Enterprise organization | $2.00 per seat | Yes, pay as you go |
Credits, expiry and what a leak can cost
Included credits are applied before any paid usage, and they can also be spent on other Hugging Face compute such as Inference Endpoints and Spaces hardware. Purchased credits have an expiry date too: unused credit is removed when it expires, and with automatic recharge switched on, that drop can trigger a new charge to your card. Compute is billed separately from the PRO subscription, with invoices at the start of each month.
The billing documentation does not describe a spending limit for a personal account; only Team and Enterprise admins can set one, and they can also switch off providers they do not want. That is the one place a rival is plainly better: OpenRouter lets you cap each key, and Mistral can cap a single key or workspace. On a personal Hugging Face account your real ceiling is the credit you bought, so leave automatic recharge off until you trust your own rate limits. You can see last month's spend by model and provider under Settings, Inference Providers.
Pick the model and the provider in the name
Each model can be served by several companies, and the model string decides who gets the request. With no suffix, Hugging Face balances price, speed and reliability. Add :fastest for the highest throughput, :cheapest for the lowest price, or a provider name such as :novita to pin one. Pinning is worth it once you depend on the output, because different providers can run the same model with different settings and limits. Keep the full string in a variable so you can change it without a deploy.
The OpenAI-compatible route covers chat completions only. For images, embeddings or speech, use the @huggingface/inference package, which takes the same token. If your app belongs to a Team or Enterprise organization, keep using your own token and add the X-HF-Bill-To header with the organization name so the usage lands on its bill; the organization's provider settings then override yours.
// app/api/ask/route.ts
import OpenAI from 'openai'
const hf = new OpenAI({
baseURL: 'https://router.huggingface.co/v1',
apiKey: process.env.HF_TOKEN,
})
export async function POST(req: Request) {
// Check the session and a per-user rate limit here.
const { question } = await req.json()
const res = await hf.chat.completions.create({
model: process.env.HF_MODEL ?? 'deepseek-ai/DeepSeek-V4.1-Flash:cheapest',
messages: [{ role: 'user', content: question }],
})
return Response.json({ text: res.choices[0]?.message?.content ?? '' })
}Expiry and leaks
A Hugging Face token that goes unused for a year expires on its own, and every use resets that clock. You get an email 30 days before, and an expired token shows an Invalidated badge and fails like a wrong one. An app that calls the router daily never hits this, but a staging token you forget about will.
If your token leaks, open Access Tokens, choose Manage and delete or refresh it, then update HF_TOKEN on your host. If you find someone else's token in a public repository, you can revoke it for them: a POST to huggingface.co/api/credentials/revoke with the token in a credentials list kills it everywhere and emails the owner, without needing any access to their account. A fine-grained token with only the inference permission limits the damage to spending your credit; a leaked write token could also change or delete your models.
What Shipyard does here
Shipyard's AI step currently writes Anthropic, OpenAI or OpenRouter keys into your host. Hugging Face is not on that list, so after a launch you add HF_TOKEN and HF_MODEL to the host yourself with the steps above. If you would rather have Shipyard handle the key, OpenRouter also serves many open models; choose it as the provider and the key goes into your host on the server side only.
Sources
- Hugging Face Hub docs: user access tokenshuggingface.co
- Hugging Face changelog: token presetshuggingface.co
- Hugging Face docs: Inference Providershuggingface.co
- Hugging Face docs: Inference Providers pricing and billinghuggingface.co
- Hugging Face docs: Inference Providers hub integrationhuggingface.co
- Hugging Face Hub docs: billinghuggingface.co
- Hugging Face pricinghuggingface.co
- Hugging Face forum: exceeded your monthly included creditsdiscuss.huggingface.co
Launch in an hour, not a weekend
Shipyard connects your accounts once, then sets up the domain, hosting, database, email and payments for every new product.