Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ import { Render, PackageManagers } from "~/components";

This guide provides an overview of how to use the latest Cloudflare Workers AI Gateway binding methods. You will learn how to set up an AI Gateway binding, access new methods, and integrate them into your Workers.

## Prerequisites

- Install and use the `@cloudflare/workers-types` library, version `4.20250124.3` or above.

## 1. Add an AI Binding to your Worker

To connect your Worker to Workers AI, add the following to your [Wrangler configuration file](/workers/wrangler/configuration/):
Expand All @@ -29,6 +25,8 @@ binding = "AI"

This configuration sets up the AI binding accessible in your Worker code as `env.AI`.

<Render file="wrangler-typegen" product="workers" />

## 2. Basic Usage with Workers AI + Gateway

To perform an inference task using Workers AI and an AI Gateway, you can use the following code:
Expand Down Expand Up @@ -78,7 +76,7 @@ gateway.patchLog('my-log-id', {

### 3.2. `getLog`: Read Log Details

The `getLog` method retrieves details of a specific log ID. It returns an object of type `Promise<AiGatewayLog>`. You can import the `AiGatewayLog` type from the `@cloudflare/workers-types` library.
The `getLog` method retrieves details of a specific log ID. It returns an object of type `Promise<AiGatewayLog>`. If this type is missing, ensure you have run [`wrangler types`](/workers/languages/typescript/#generate-types).

```typescript
const log = await gateway.getLog("my-log-id");
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/d1/worker-api/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Refer to the relevant sections for the API documentation.

## TypeScript support

D1 Worker Bindings API is fully-typed via the [`@cloudflare/workers-types`](/workers/languages/typescript/#typescript) package, and also supports [generic types](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types) as part of its TypeScript API. A generic type allows you to provide an optional `type parameter` so that a function understands the type of the data it is handling.
D1 Worker Bindings API is fully-typed via the runtime types generated by running [`wrangler types`](/workers/languages/typescript/#typescript) package, and also supports [generic types](https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-types) as part of its TypeScript API. A generic type allows you to provide an optional `type parameter` so that a function understands the type of the data it is handling.

When using the query statement methods [`D1PreparedStatement::run`](/d1/worker-api/prepared-statements/#run), [`D1PreparedStatement::raw`](/d1/worker-api/prepared-statements/#raw) and [`D1PreparedStatement::first`](/d1/worker-api/prepared-statements/#first), you can provide a type representing each database row. D1's API will [return the result object](/d1/worker-api/return-object/#d1result) with the correct type.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,17 +120,11 @@ In order to access bindings in a deployed application, you will need to [configu

### Add bindings to TypeScript projects

To get proper type support, you need to create a new `env.d.ts` file in the root of your project and declare a [binding](/pages/functions/bindings/).
To get proper type support, you need to create a new `env.d.ts` file in the root of your project and declare a [binding](/pages/functions/bindings/). Make sure you have generated Cloudflare runtime types by running [`wrangler types`](/pages/functions/typescript/).

The following is an example of adding a `KVNamespace` binding:

```ts null {9}
import {
CfProperties,
Request,
ExecutionContext,
KVNamespace,
} from "@cloudflare/workers-types";

declare module "h3" {
interface H3EventContext {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ The following code block shows an example of accessing a KV namespace in QwikCit
// ...

export const useGetServerTime = routeLoader$(({ platform }) => {
// the type `KVNamespace` comes from the @cloudflare/workers-types package
// the type `KVNamespace` comes from runtime types generated by running `wrangler types`
const { MY_KV } = (platform.env as { MY_KV: KVNamespace }));

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,11 @@ Use bindings in Astro components and API routes by using `context.locals` from [

Refer to the following example of how to access a KV namespace with TypeScript.

First, you need to define Cloudflare runtime and KV type by updating the `env.d.ts`:
First, you need to define Cloudflare runtime and KV type by updating the `env.d.ts`. Make sure you have generated Cloudflare runtime types by running [`wrangler types`](/pages/functions/typescript/).

```typescript
/// <reference types="astro/client" />

type KVNamespace = import("@cloudflare/workers-types").KVNamespace;
type ENV = {
// replace `MY_KV` with your KV namespace
MY_KV: KVNamespace;
Expand All @@ -137,7 +136,6 @@ You can then access your KV from an API endpoint in the following way:
import type { APIContext } from "astro";

export async function get({ locals }: APIContext) {
// the type KVNamespace comes from the @cloudflare/workers-types package
const { MY_KV } = locals.runtime.env;

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,32 +30,7 @@ Add bindings to your Pages project by adding them to your [Wrangler configuratio

## TypeScript type declarations for bindings

To ensure that the `env` object from `getRequestContext().env` above has accurate TypeScript types, install [`@cloudflare/workers-types`](https://www.npmjs.com/package/@cloudflare/workers-types) and create a [TypeScript declaration file](https://www.typescriptlang.org/docs/handbook/2/type-declarations.html).

Install Workers Types:

```sh
npm install --save-dev @cloudflare/workers-types
```

Add Workers Types to your `tsconfig.json` file, replacing the date below with your project's [compatibility date](/workers/configuration/compatibility-dates/):

```diff title="tsconfig.json"
"types": [
+ "@cloudflare/workers-types/2024-07-29"
]
```

Create an `env.d.ts` file in the root directory of your Next.js app, and explicitly declare the type of each binding:

```ts title="env.d.ts"
interface CloudflareEnv {
MY_KV_1: KVNamespace;
MY_KV_2: KVNamespace;
MY_R2: R2Bucket;
MY_DO: DurableObjectNamespace;
}
```
To ensure that the `env` object from `getRequestContext().env` above has accurate TypeScript types, make sure you have generated types by running [`wrangler types`](/workers/languages/typescript/#generate-types) and followed the setup steps.

## Other Cloudflare APIs (`cf`, `ctx`)

Expand Down
6 changes: 3 additions & 3 deletions src/content/docs/pub-sub/learning/integrate-workers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ sidebar:
order: 2
---

import { WranglerConfig } from "~/components";
import { WranglerConfig, Render } from "~/components";

Once of the most powerful features of Pub/Sub is the ability to connect [Cloudflare Workers](/workers/) — powerful serverless functions that run on the edge — and filter, aggregate and mutate every message published to that broker. Workers can also mirror those messages to other sources, including writing to [Cloudflare R2 storage](/r2/), external databases, or other cloud services beyond Cloudflare, making it easy to persist or analyze incoming message payloads and data at scale.

Expand Down Expand Up @@ -129,6 +129,8 @@ BROKER_PUBLIC_KEYS = '''{

</WranglerConfig>

<Render file="wrangler-typegen" product="workers" />

With the `BROKER_PUBLIC_KEYS` environmental variable set, we can now access these in our Worker code. The [`@cloudflare/pubsub`](https://www.npmjs.com/package/@cloudflare/pubsub) package allows you to authenticate the incoming request against your Broker's
public keys.

Expand All @@ -144,8 +146,6 @@ our Worker code directly:
```typescript
// An example that shows how to consume and transform Pub/Sub messages from a Cloudflare Worker.

/// <reference types="@cloudflare/workers-types" />

import { isValidBrokerRequest, PubSubMessage } from "@cloudflare/pubsub";

async function pubsub(
Expand Down
4 changes: 1 addition & 3 deletions src/content/docs/vectorize/reference/client-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,4 @@ Refer to the [bindings documentation](/workers/wrangler/configuration/#vectorize

## TypeScript Types

New Workers projects created via `npm create cloudflare@latest` automatically include the relevant TypeScript types for Vectorize.

Older projects, or non-Workers projects looking to use Vectorize's [REST API](https://developers.cloudflare.com/api/resources/vectorize/subresources/indexes/methods/list/) in a TypeScript project, should ensure `@cloudflare/workers-types` version `4.20230922.0` or later is installed.
<Render file="wrangler-typegen" product="workers" />
2 changes: 1 addition & 1 deletion src/content/docs/workers/runtime-apis/request.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ An object containing Cloudflare-specific properties that can be set on the `Requ
fetch(event.request, { cf: { scrapeShield: false } })
```

Invalid or incorrectly-named keys in the `cf` object will be silently ignored. Consider using TypeScript and [`@cloudflare/workers-types`](https://www.npmjs.com/package/@cloudflare/workers-types) to ensure proper use of the `cf` object.
Invalid or incorrectly-named keys in the `cf` object will be silently ignored. Consider using TypeScript and generating types by running [`wrangler types`](/workers/languages/typescript/#generate-types) to ensure proper use of the `cf` object.



Expand Down
39 changes: 29 additions & 10 deletions src/content/docs/workers/runtime-apis/rpc/typescript.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,44 @@ head:
content: Workers RPC — TypeScript
description: How TypeScript types for your Worker or Durable Object's RPC
methods are generated and exposed to clients

---

The [`@cloudflare/workers-types`](https://www.npmjs.com/package/@cloudflare/workers-types) package provides the `Service` and `DurableObjectNamespace` types, each of which accepts a single type parameter for the server-side [`WorkerEntrypoint`](/workers/runtime-apis/bindings/service-bindings/rpc) or [`DurableObject`](/durable-objects/best-practices/create-durable-object-stubs-and-send-requests/#call-rpc-methods) types.
import { PackageManagers } from "~/components";

Running [`wrangler types`](/workers/languages/typescript/#generate-types) generates runtime types including the `Service` and `DurableObjectNamespace` types, each of which accepts a single type parameter for the [`WorkerEntrypoint`](/workers/runtime-apis/bindings/service-bindings/rpc) or [`DurableObject`](/durable-objects/best-practices/create-durable-object-stubs-and-send-requests/#call-rpc-methods) types.

Using higher-order types, we automatically generate client-side stub types (e.g., forcing all methods to be async).

For example:
[`wrangler types`](/workers/languages/typescript/#generate-types) also generates types for the `env` object. You can pass in the path to the config files of the Worker or Durable Object being called so that the generated types include the type parameters for the `Service` and `DurableObjectNamespace` types.

For example, if your client Worker had bindings to a Worker in `../sum-worker/` and a Durable Object in `../counter/`, you should generate types for the client Worker's `env` by running:

<PackageManagers
type="exec"
pkg="wrangler"
args={
"types -c ./client/wrangler.jsonc -c ../sum-worker/wrangler.jsonc -c ../counter/wrangler.jsonc"
}
/>

```ts
This will produce a `worker-configuration.d.ts` file that includes:

```ts title="worker-configuration.d.ts"
interface Env {
SUM_SERVICE: Service<SumService>;
COUNTER_OBJECT: DurableObjectNamespace<Counter>
SUM_SERVICE: Service<import("../sum-worker/src/index").SumService>;
COUNTER_OBJECT: DurableObjectNamespace<
import("../counter/src/index").Counter
>;
}
```

Now types for RPC method like the `env.SUM_SERVICE.sum` method will be exposed to the client Worker.

```ts title="src/index.ts"
export default {
async fetch(req, env, ctx): Promise<Response> {
const result = await env.SUM_SERVICE.sum(1, 2);
return new Response(result.toString());
}
async fetch(req, env, ctx): Promise<Response> {
const result = await env.SUM_SERVICE.sum(1, 2);
return new Response(result.toString());
},
} satisfies ExportedHandler<Env>;
```
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ If you are using TypeScript, update your `tsconfig.json` to include the correct
"compilerOptions": {
...,
"types": [
"@cloudflare/workers-types/experimental"
...
- "vitest-environment-miniflare/globals"
+ "@cloudflare/vitest-pool-workers"
]
Expand Down
9 changes: 6 additions & 3 deletions src/content/docs/workflows/build/workers-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -212,17 +212,20 @@ script_name = "billing-worker"

</WranglerConfig>

<Render file="wrangler-typegen" product="workers" />

## Workflow

:::note

Ensure you have `@cloudflare/workers-types` version `4.20241022.0` or later installed when binding to Workflows from within a Workers project.
Ensure you have a compatibility date `2024-10-22` or later installed when binding to Workflows from within a Workers project.

:::

The `Workflow` type provides methods that allow you to create, inspect the status, and manage running Workflow instances from within a Worker script.

```ts
It is part of the generated types produced by [`wrangler types`](/workers/wrangler/commands/#types).

```ts title="./worker-configuration.d.ts"
interface Env {
// The 'MY_WORKFLOW' variable should match the "binding" value set in the Wrangler config file
MY_WORKFLOW: Workflow;
Expand Down
1 change: 0 additions & 1 deletion src/content/docs/workflows/examples/backup-d1.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ Here is a minimal package.json:
```json
{
"devDependencies": {
"@cloudflare/workers-types": "^4.20241224.0",
"wrangler": "^3.99.0"
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/content/docs/workflows/examples/send-invoices.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ sidebar:
description: Send invoice when shopping cart is checked out and paid for
---

import { TabItem, Tabs, WranglerConfig } from "~/components";
import { TabItem, Tabs, WranglerConfig, Render } from "~/components";

In this example, we implement a Workflow for an e-commerce website that is triggered every time a shopping cart is created.

Expand Down Expand Up @@ -190,7 +190,6 @@ Here's a minimal package.json:
```json
{
"devDependencies": {
"@cloudflare/workers-types": "^4.20241022.0",
"wrangler": "^3.83.0"
},
"dependencies": {
Expand Down Expand Up @@ -219,3 +218,5 @@ name = "SEND_EMAIL"
```

</WranglerConfig>

<Render file="wrangler-typegen" product="workers" />
1 change: 1 addition & 0 deletions src/content/partials/workers/wrangler-typegen.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
If you're using TypeScript, run [`wrangler types`](/workers/wrangler/commands/#types) whenever you modify your Wrangler configuration file. This generates types for the `env` object based on your bindings, as well as [runtime types](/workers/languages/typescript/).