← Blog

How to Deploy a Claude API Serverless Function

2026-11-24 · 5 min read · SubToAPI Team

Deploying a Claude API Call as a Serverless Function

Deploying the Claude API inside a serverless function means wrapping your API call in a handler that your cloud provider runs on demand — no server to manage, no process to keep alive. The core pattern is the same everywhere: write a function that reads the request, calls the Claude API (or a gateway in front of it), and returns the response, then deploy it to AWS Lambda, Vercel Functions, Cloudflare Workers, or similar.

The practical challenges aren't the API call itself — it's handling secrets safely, dealing with execution time limits when responses are long, and deciding whether you need streaming. This guide walks through a working deployment on the three most common platforms, plus the gotchas that trip people up the first time.

Why Serverless Makes Sense for Claude API Calls

Most apps calling an LLM API don't need a persistent server. Requests are bursty, latency is dominated by the model's response time rather than your code, and you want to scale to zero when nobody's using it. Serverless functions fit this well:

The tradeoff is execution time limits (Lambda's default is 3 seconds unless you raise it, Vercel's hobby tier caps at 10 seconds) and no long-lived connections, which matters if you're streaming tokens back to a client.

Deploying on AWS Lambda

A minimal Lambda handler that calls an LLM API looks like this:

export const handler = async (event) => {
  const body = JSON.parse(event.body);

  const response = await fetch("https://api.example.com/v1/messages", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.API_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      model: "claude-3-5-sonnet",
      max_tokens: 1024,
      messages: [{ role: "user", content: body.prompt }]
    })
  });

  const data = await response.json();

  return {
    statusCode: 200,
    body: JSON.stringify(data)
  };
};

Key points when deploying this:

  1. Raise the timeout. Default Lambda timeout is too short for most completions. Set it to at least 30 seconds in the function configuration.
  2. Store the API key in Lambda environment variables, not in code. If you're on a team, use AWS Secrets Manager and fetch it at cold start, not per request.
  3. Watch cold starts. Node.js functions on Lambda typically cold-start in under a second, but if your package includes heavy SDKs, bundle size affects this. Keep dependencies minimal.
  4. Memory affects CPU. If your function does any JSON processing on large responses, bumping memory from 128MB to 256MB often speeds things up more than you'd expect, for negligible extra cost.

Deploy with the AWS CLI, SAM, or the Serverless Framework — any of them works fine for a single-function API wrapper like this.

Deploying on Vercel or Netlify Functions

If your frontend already lives on Vercel, a serverless function in the same repo avoids CORS issues and extra infrastructure:

// api/claude.js
export default async function handler(req, res) {
  if (req.method !== "POST") {
    return res.status(405).json({ error: "Method not allowed" });
  }

  const response = await fetch("https://api.example.com/v1/messages", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.API_KEY}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      model: "claude-3-5-sonnet",
      max_tokens: 1024,
      messages: req.body.messages
    })
  });

  const data = await response.json();
  res.status(200).json(data);
}

Add API_KEY as an environment variable in the Vercel dashboard (not .env committed to git), and deploy with vercel deploy. On the free/hobby tier, check your function's execution time limit — long completions can get cut off, in which case streaming or a paid tier with higher limits is the fix.

Deploying on Cloudflare Workers

Workers are a good fit if you need low-latency, globally distributed execution and want to stream tokens back to the client without Lambda's connection limitations:

export default {
  async fetch(request, env) {
    const { prompt } = await request.json();

    const upstream = await fetch("https://api.example.com/v1/messages", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${env.API_KEY}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        model: "claude-3-5-sonnet",
        max_tokens: 1024,
        stream: true,
        messages: [{ role: "user", content: prompt }]
      })
    });

    return new Response(upstream.body, {
      headers: { "Content-Type": "text/event-stream" }
    });
  }
};

Workers handle streaming responses natively by piping the upstream body straight through, which is harder to do cleanly on Lambda without additional configuration (Lambda response streaming exists but has more setup overhead).

Simplifying the Setup with SubToAPI

A lot of the friction in this process — key rotation, usage tracking per endpoint, rate limiting across multiple deployed functions — goes away if you call Claude through a layer built for exactly this. SubToAPI turns your Claude access into a standard HTTPS API with its own sub_live_... keys, so your serverless function doesn't need direct access to your underlying credentials:

const response = await fetch("https://api.subtoapi.app/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "claude-3-5-sonnet",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Summarize this ticket." }]
  })
});

This matters in a serverless context because it means you can issue a scoped key per function or per environment (staging, production, a specific Lambda), see usage broken down in one dashboard, and revoke a single key without touching your main account. See the quickstart for setup and the streaming docs if your function needs to pipe tokens back to a client. Plans start at €9/month for solo use, with team seats on the Team and Scale plans — check pricing for details.

Testing Before You Deploy

Before pushing to production, test the function locally:

curl -X POST http://localhost:3000/api/claude \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Write a one-sentence changelog entry"}'

Confirm your timeout, memory, and environment variables are set correctly in the deployed environment (not just locally) — the most common deployment bug with Claude-backed serverless functions is a missing env var that only shows up once you're live.

FAQ

Do I need to handle streaming in a serverless function? Only if your use case needs tokens to appear incrementally, like a chat UI. For batch jobs, summarization, or backend processing, a standard request/response is simpler and avoids platform-specific streaming quirks.

Which platform is best for calling the Claude API? Vercel or Netlify if your frontend is already there, Cloudflare Workers if you need low latency and native streaming, and AWS Lambda if you're already in the AWS ecosystem or need fine-grained control over memory and timeout settings.

How do I avoid exposing my API key in a serverless function? Store it as an environment variable in your platform's dashboard, never in committed code, and scope it as narrowly as possible. Using a gateway like SubToAPI lets you issue a dedicated key per deployed function so a leak doesn't expose your main credentials.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →