# Using Wayline from serverless functions

> Call the Wayline API from Vercel functions, AWS Lambda and Cloudflare Workers with secrets, timeouts, caching and edge-runtime compatible code.

Source: https://www.wayline.cloud/docs/guides/serverless

Serverless functions are a great place to call Wayline: your key stays server-side and you can add caching and per-user limits.

## Vercel (Next.js route handler)

```typescript
// app/api/distance/route.ts
export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const url = new URL("https://api.wayline.cloud/v1/distance");
  url.searchParams.set("origin", searchParams.get("origin") ?? "");
  url.searchParams.set("destination", searchParams.get("destination") ?? "");
  const res = await fetch(url, {
    headers: { Authorization: `Bearer ${process.env.WAYLINE_API_KEY}` },
    signal: AbortSignal.timeout(5000),
  });
  return new Response(res.body, { status: res.status, headers: { "content-type": "application/json" } });
}
```

Set `WAYLINE_API_KEY` in **Project Settings → Environment Variables**. Validate and authenticate your own users before proxying.

## AWS Lambda (Node.js 20+)

```javascript
export const handler = async (event) => {
  const { origin, destination } = event.queryStringParameters ?? {};
  const url = `https://api.wayline.cloud/v1/distance?origin=${encodeURIComponent(origin)}&destination=${encodeURIComponent(destination)}`;
  const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.WAYLINE_API_KEY}` }, signal: AbortSignal.timeout(5000) });
  return { statusCode: res.status, headers: { "content-type": "application/json" }, body: await res.text() };
};
```

Store the key in AWS Secrets Manager or SSM Parameter Store and load it at cold start.

## Cloudflare Workers

```typescript
export default {
  async fetch(req: Request, env: { WAYLINE_API_KEY: string }) {
    const { searchParams } = new URL(req.url);
    const url = new URL("https://api.wayline.cloud/v1/distance");
    url.searchParams.set("origin", searchParams.get("origin") ?? "");
    url.searchParams.set("destination", searchParams.get("destination") ?? "");
    const cache = caches.default;
    const cacheKey = new Request(url.toString());
    let res = await cache.match(cacheKey);
    if (!res) {
      res = await fetch(url, { headers: { Authorization: `Bearer ${env.WAYLINE_API_KEY}` } });
      if (res.ok) {
        res = new Response(res.body, res);
        res.headers.set("Cache-Control", "max-age=86400");
        await cache.put(cacheKey, res.clone());
      }
    }
    return res;
  },
};
```

Add the key with `wrangler secret put WAYLINE_API_KEY`. The [TypeScript SDK](/docs/sdks/javascript) runs on Workers, Vercel Edge, Deno and Bun.

## Tips

- Reuse connections: create clients outside the handler.
- Set timeouts shorter than your function's limit.
- Cache results ([Caching](/docs/concepts/caching)) — cold starts plus network calls add up.
