Skip to content

Commit 60d7fa9

Browse files
[wrangler] Update instructions for accessing runtime types (#20082)
* update references to@cloudflare/workers-types to wrangler types * Update src/content/docs/workers/runtime-apis/rpc/typescript.mdx Co-authored-by: ToriLindsay <[email protected]> --------- Co-authored-by: ToriLindsay <[email protected]>
1 parent b2a797c commit 60d7fa9

File tree

15 files changed

+53
-67
lines changed

15 files changed

+53
-67
lines changed

src/content/docs/ai-gateway/integrations/worker-binding-methods.mdx

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,6 @@ import { Render, PackageManagers } from "~/components";
88

99
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.
1010

11-
## Prerequisites
12-
13-
- Install and use the `@cloudflare/workers-types` library, version `4.20250124.3` or above.
14-
1511
## 1. Add an AI Binding to your Worker
1612

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

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

28+
<Render file="wrangler-typegen" product="workers" />
29+
3230
## 2. Basic Usage with Workers AI + Gateway
3331

3432
To perform an inference task using Workers AI and an AI Gateway, you can use the following code:
@@ -82,7 +80,7 @@ gateway.patchLog("my-log-id", {
8280

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

85-
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.
83+
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).
8684

8785
```typescript
8886
const log = await gateway.getLog("my-log-id");

src/content/docs/d1/worker-api/index.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Refer to the relevant sections for the API documentation.
1818

1919
## TypeScript support
2020

21-
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.
21+
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.
2222

2323
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.
2424

src/content/docs/pages/framework-guides/deploy-a-nuxt-site.mdx

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -125,17 +125,11 @@ In order to access bindings in a deployed application, you will need to [configu
125125

126126
### Add bindings to TypeScript projects
127127

128-
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/).
128+
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/).
129129

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

132132
```ts null {9}
133-
import {
134-
CfProperties,
135-
Request,
136-
ExecutionContext,
137-
KVNamespace,
138-
} from "@cloudflare/workers-types";
139133

140134
declare module "h3" {
141135
interface H3EventContext {

src/content/docs/pages/framework-guides/deploy-a-qwik-site.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ The following code block shows an example of accessing a KV namespace in QwikCit
7373
// ...
7474

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

7979
return {

src/content/docs/pages/framework-guides/deploy-an-astro-site.mdx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,12 +118,11 @@ Use bindings in Astro components and API routes by using `context.locals` from [
118118

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

121-
First, you need to define Cloudflare runtime and KV type by updating the `env.d.ts`:
121+
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/).
122122

123123
```typescript
124124
/// <reference types="astro/client" />
125125

126-
type KVNamespace = import("@cloudflare/workers-types").KVNamespace;
127126
type ENV = {
128127
// replace `MY_KV` with your KV namespace
129128
MY_KV: KVNamespace;
@@ -142,7 +141,6 @@ You can then access your KV from an API endpoint in the following way:
142141
import type { APIContext } from "astro";
143142

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

148146
return {

src/content/docs/pages/framework-guides/nextjs/ssr/bindings.mdx

Lines changed: 1 addition & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -35,32 +35,7 @@ Add bindings to your Pages project by adding them to your [Wrangler configuratio
3535

3636
## TypeScript type declarations for bindings
3737

38-
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).
39-
40-
Install Workers Types:
41-
42-
```sh
43-
npm install --save-dev @cloudflare/workers-types
44-
```
45-
46-
Add Workers Types to your `tsconfig.json` file, replacing the date below with your project's [compatibility date](/workers/configuration/compatibility-dates/):
47-
48-
```diff title="tsconfig.json"
49-
"types": [
50-
+ "@cloudflare/workers-types/2024-07-29"
51-
]
52-
```
53-
54-
Create an `env.d.ts` file in the root directory of your Next.js app, and explicitly declare the type of each binding:
55-
56-
```ts title="env.d.ts"
57-
interface CloudflareEnv {
58-
MY_KV_1: KVNamespace;
59-
MY_KV_2: KVNamespace;
60-
MY_R2: R2Bucket;
61-
MY_DO: DurableObjectNamespace;
62-
}
63-
```
38+
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.
6439

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

src/content/docs/pub-sub/learning/integrate-workers.mdx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ sidebar:
55
order: 2
66
---
77

8-
import { WranglerConfig } from "~/components";
8+
import { WranglerConfig, Render } from "~/components";
99

1010
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.
1111

@@ -129,6 +129,8 @@ BROKER_PUBLIC_KEYS = '''{
129129

130130
</WranglerConfig>
131131

132+
<Render file="wrangler-typegen" product="workers" />
133+
132134
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
133135
public keys.
134136

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

147-
/// <reference types="@cloudflare/workers-types" />
148-
149149
import { isValidBrokerRequest, PubSubMessage } from "@cloudflare/pubsub";
150150

151151
async function pubsub(

src/content/docs/vectorize/reference/client-api.mdx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,4 @@ Refer to the [bindings documentation](/workers/wrangler/configuration/#vectorize
218218

219219
## TypeScript Types
220220

221-
New Workers projects created via `npm create cloudflare@latest` automatically include the relevant TypeScript types for Vectorize.
222-
223-
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.
221+
<Render file="wrangler-typegen" product="workers" />

src/content/docs/workers/runtime-apis/request.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ An object containing Cloudflare-specific properties that can be set on the `Requ
9999
fetch(event.request, { cf: { scrapeShield: false } })
100100
```
101101

102-
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.
102+
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.
103103

104104

105105

src/content/docs/workers/runtime-apis/rpc/typescript.mdx

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,44 @@ head:
88
content: Workers RPC — TypeScript
99
description: How TypeScript types for your Worker or Durable Object's RPC
1010
methods are generated and exposed to clients
11-
1211
---
1312

14-
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.
13+
import { PackageManagers } from "~/components";
14+
15+
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.
1516

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

18-
For example:
19+
[`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.
20+
21+
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:
22+
23+
<PackageManagers
24+
type="exec"
25+
pkg="wrangler"
26+
args={
27+
"types -c ./client/wrangler.jsonc -c ../sum-worker/wrangler.jsonc -c ../counter/wrangler.jsonc"
28+
}
29+
/>
1930

20-
```ts
31+
This will produce a `worker-configuration.d.ts` file that includes:
32+
33+
```ts title="worker-configuration.d.ts"
2134
interface Env {
22-
SUM_SERVICE: Service<SumService>;
23-
COUNTER_OBJECT: DurableObjectNamespace<Counter>
35+
SUM_SERVICE: Service<import("../sum-worker/src/index").SumService>;
36+
COUNTER_OBJECT: DurableObjectNamespace<
37+
import("../counter/src/index").Counter
38+
>;
2439
}
40+
```
41+
42+
Now types for RPC method like the `env.SUM_SERVICE.sum` method will be exposed to the client Worker.
2543

44+
```ts title="src/index.ts"
2645
export default {
27-
async fetch(req, env, ctx): Promise<Response> {
28-
const result = await env.SUM_SERVICE.sum(1, 2);
29-
return new Response(result.toString());
30-
}
46+
async fetch(req, env, ctx): Promise<Response> {
47+
const result = await env.SUM_SERVICE.sum(1, 2);
48+
return new Response(result.toString());
49+
},
3150
} satisfies ExportedHandler<Env>;
3251
```

0 commit comments

Comments
 (0)