Skip to content

Commit 5ee2391

Browse files
committed
PR #21258 - hono examples fixes
1 parent 4885dba commit 5ee2391

14 files changed

+244
-273
lines changed

src/content/docs/workers/examples/103-early-hints.mdx

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def on_fetch(request):
139139
</TabItem> <TabItem label="Hono" icon="seti:typescript">
140140

141141
```ts
142-
import { Hono } from 'hono';
142+
import { Hono } from "hono";
143143

144144
const app = new Hono();
145145

@@ -159,22 +159,21 @@ const HTML = `
159159
`;
160160

161161
// Serve CSS file
162-
app.get('/test.css', (c) => {
163-
return c.body(CSS, {
164-
headers: {
165-
"content-type": "text/css",
166-
},
167-
});
162+
app.get("/test.css", (c) => {
163+
return c.body(CSS, {
164+
headers: {
165+
"content-type": "text/css",
166+
},
167+
});
168168
});
169169

170170
// Serve HTML with early hints
171-
app.get('*', (c) => {
172-
return c.body(HTML, {
173-
headers: {
174-
"content-type": "text/html",
175-
"link": "</test.css>; rel=preload; as=style",
176-
},
177-
});
171+
app.get("*", (c) => {
172+
return c.html(HTML, {
173+
headers: {
174+
link: "</test.css>; rel=preload; as=style",
175+
},
176+
});
178177
});
179178

180179
export default app;

src/content/docs/workers/examples/ab-testing.mdx

Lines changed: 12 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -147,59 +147,44 @@ const app = new Hono();
147147

148148
const NAME = "myExampleWorkersABTest";
149149

150+
// Enable passthrough to allow direct access to control and test routes
151+
app.all("/control/*", (c) => fetch(c.req.raw));
152+
app.all("/test/*", (c) => fetch(c.req.raw));
153+
150154
// Middleware to handle A/B testing logic
151155
app.use("*", async (c) => {
152-
// Enable Passthrough to allow direct access to control and test routes
153-
if (c.req.path.startsWith("/control") || c.req.path.startsWith("/test")) {
154-
return fetch(c.req.raw);
155-
}
156+
const url = new URL(c.req.url);
156157

157158
// Determine which group this requester is in
158159
const abTestCookie = getCookie(c, NAME);
159160

160161
if (abTestCookie === "control") {
161162
// User is in control group
162-
c.req.path = "/control" + c.req.path;
163-
return fetch(url);
163+
url.pathname = "/control" + c.req.path;
164164
} else if (abTestCookie === "test") {
165165
// User is in test group
166-
url.pathname = "/test" + url.pathname;
167-
return fetch(c.req.url);
166+
url.pathname = "/test" + c.req.path;
168167
} else {
169168
// If there is no cookie, this is a new client
170169
// Choose a group and set the cookie (50/50 split)
171170
const group = Math.random() < 0.5 ? "test" : "control";
172171

173172
// Update URL path based on assigned group
174173
if (group === "control") {
175-
c.req.path = "/control" + c.req.path;
174+
url.pathname = "/control" + c.req.path;
176175
} else {
177-
c.req.path = "/test" + c.req.path;
176+
url.pathname = "/test" + c.req.path;
178177
}
179178

180-
// Fetch from origin with modified path
181-
const res = await fetch(c.req.url);
182-
183-
// Create a new response to avoid immutability issues
184-
const newResponse = new Response(res.body, res);
185-
186179
// Set cookie to enable persistent A/B sessions
187180
setCookie(c, NAME, group, {
188181
path: "/",
189-
// Add additional cookie options as needed:
190-
// secure: true,
191-
// httpOnly: true,
192-
// sameSite: 'strict',
193182
});
183+
}
194184

195-
// Copy the Set-Cookie header to the response
196-
newResponse.headers.set(
197-
"Set-Cookie",
198-
c.res.headers.get("Set-Cookie") || "",
199-
);
185+
const res = await fetch(url);
200186

201-
return newResponse;
202-
}
187+
return c.body(res.body, res);
203188
});
204189

205190
export default app;

src/content/docs/workers/examples/accessing-the-cloudflare-object.mdx

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,7 @@ export default {
6161
```ts
6262
import { Hono } from "hono";
6363

64-
type Bindings = {};
65-
66-
const app = new Hono<{ Bindings: Bindings }>();
64+
const app = new Hono();
6765

6866
app.get("*", async (c) => {
6967
// Access the raw request to get the cf object

src/content/docs/workers/examples/aggregate-requests.mdx

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -61,26 +61,24 @@ export default {
6161
</TabItem> <TabItem label="Hono" icon="seti:typescript">
6262

6363
```ts
64-
import { Hono } from 'hono';
65-
66-
type Bindings = {};
67-
68-
const app = new Hono<{ Bindings: Bindings }>();
69-
70-
app.get('*', async (c) => {
71-
// someHost is set up to return JSON responses
72-
const someHost = "https://jsonplaceholder.typicode.com";
73-
const url1 = someHost + "/todos/1";
74-
const url2 = someHost + "/todos/2";
75-
76-
// Fetch both URLs concurrently
77-
const responses = await Promise.all([fetch(url1), fetch(url2)]);
78-
79-
// Parse JSON responses concurrently
80-
const results = await Promise.all(responses.map(r => r.json()));
81-
82-
// Return aggregated results
83-
return c.json(results);
64+
import { Hono } from "hono";
65+
66+
const app = new Hono();
67+
68+
app.get("*", async (c) => {
69+
// someHost is set up to return JSON responses
70+
const someHost = "https://jsonplaceholder.typicode.com";
71+
const url1 = someHost + "/todos/1";
72+
const url2 = someHost + "/todos/2";
73+
74+
// Fetch both URLs concurrently
75+
const responses = await Promise.all([fetch(url1), fetch(url2)]);
76+
77+
// Parse JSON responses concurrently
78+
const results = await Promise.all(responses.map((r) => r.json()));
79+
80+
// Return aggregated results
81+
return c.json(results);
8482
});
8583

8684
export default app;

src/content/docs/workers/examples/basic-auth.mdx

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,7 @@ import { auth } from 'hono/basic-auth';
347347
// Define environment interface
348348
interface Env {
349349
Bindings: {
350+
USERNAME: string;
350351
PASSWORD: string;
351352
};
352353
}
@@ -358,20 +359,23 @@ app.get('/', (c) => {
358359
return c.text("Anyone can access the homepage.");
359360
});
360361
361-
// Logout route
362-
app.get('/logout', (c) => {
363-
return c.text("Logged out.", 401);
364-
});
365-
366362
// Admin route - protected with Basic Auth
367-
app.get('/admin', async (c, next) => {
368-
return basicAuth({ username: c.env.USERNAME, password: c.env.PASSWORD })(c, next);
369-
});
363+
app.get(
364+
"/admin",
365+
async (c, next) => {
366+
const auth = basicAuth({
367+
username: c.env.USERNAME,
368+
password: c.env.PASSWORD
369+
})
370+
371+
return await auth(c, next);
372+
},
373+
(c) => {
374+
return c.text("🎉 You have private access!", 200, {
375+
"Cache-Control": "no-store",
376+
});
377+
}
370378
371-
// Handle 404 for any other routes
372-
app.notFound((c) => {
373-
return c.text("Not Found.", 404);
374-
});
375379
376380
export default app;
377381
````

src/content/docs/workers/examples/block-on-tls.mdx

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -74,31 +74,28 @@ export default {
7474
```ts
7575
import { Hono } from "hono";
7676

77-
type Bindings = {};
78-
79-
const app = new Hono<{ Bindings: Bindings }>();
77+
const app = new Hono();
8078

8179
// Middleware to check TLS version
8280
app.use("*", async (c, next) => {
83-
try {
84-
// Access the raw request to get the cf object with TLS info
85-
const request = c.req.raw;
86-
const tlsVersion = request.cf?.tlsVersion;
87-
88-
// Allow only TLS versions 1.2 and 1.3
89-
if (tlsVersion !== "TLSv1.2" && tlsVersion !== "TLSv1.3") {
90-
return c.text("Please use TLS version 1.2 or higher.", 403);
91-
}
81+
// Access the raw request to get the cf object with TLS info
82+
const request = c.req.raw;
83+
const tlsVersion = request.cf?.tlsVersion;
84+
85+
// Allow only TLS versions 1.2 and 1.3
86+
if (tlsVersion !== "TLSv1.2" && tlsVersion !== "TLSv1.3") {
87+
return c.text("Please use TLS version 1.2 or higher.", 403);
88+
}
9289

93-
// Continue to the next handler if TLS version is acceptable
94-
return next();
95-
} catch (err: any) {
96-
// Handle errors (especially in preview mode where request.cf might not exist)
90+
await next();
91+
92+
});
93+
94+
app.onError((err, c) => {
9795
console.error(
9896
"request.cf does not exist in the previewer, only in production",
9997
);
10098
return c.text(`Error in workers script: ${err.message}`, 500);
101-
}
10299
});
103100

104101
app.get("/", async (c) => {

src/content/docs/workers/examples/bulk-origin-proxy.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ app.all("*", async (c) => {
101101
}
102102

103103
// Otherwise, process request as normal
104-
return fetch(c.req.raw);
104+
return proxy(c.req.raw);
105105
});
106106

107107
export default app;

src/content/docs/workers/examples/bulk-redirects.mdx

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -102,38 +102,38 @@ async def on_fetch(request):
102102
</TabItem> <TabItem label="Hono" icon="seti:typescript">
103103

104104
```ts
105-
import { Hono } from 'hono';
105+
import { Hono } from "hono";
106106

107107
const app = new Hono();
108108

109109
// Configure your redirects
110110
const externalHostname = "examples.cloudflareworkers.com";
111111

112112
const redirectMap = new Map([
113-
["/bulk1", `https://${externalHostname}/redirect2`],
114-
["/bulk2", `https://${externalHostname}/redirect3`],
115-
["/bulk3", `https://${externalHostname}/redirect4`],
116-
["/bulk4", "https://google.com"],
113+
["/bulk1", `https://${externalHostname}/redirect2`],
114+
["/bulk2", `https://${externalHostname}/redirect3`],
115+
["/bulk3", `https://${externalHostname}/redirect4`],
116+
["/bulk4", "https://google.com"],
117117
]);
118118

119119
// Middleware to handle redirects
120-
app.use('*', async (c, next) => {
121-
const path = new URL(c.req.url).pathname;
122-
const location = redirectMap.get(path);
120+
app.use("*", async (c, next) => {
121+
const path = c.req.path;
122+
const location = redirectMap.get(path);
123123

124-
if (location) {
125-
// If path is in our redirect map, perform the redirect
126-
return c.redirect(location, 301);
127-
}
124+
if (location) {
125+
// If path is in our redirect map, perform the redirect
126+
return c.redirect(location, 301);
127+
}
128128

129-
// Otherwise, continue to the next handler
130-
await next();
129+
// Otherwise, continue to the next handler
130+
await next();
131131
});
132132

133133
// Default handler for requests that don't match any redirects
134-
app.all('*', async (c) => {
135-
// Pass through to origin
136-
return fetch(c.req.raw);
134+
app.all("*", async (c) => {
135+
// Pass through to origin
136+
return fetch(c.req.raw);
137137
});
138138

139139
export default app;

src/content/docs/workers/examples/cache-api.mdx

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -136,13 +136,8 @@ async def on_fetch(request, _env, ctx):
136136

137137
```ts
138138
import { Hono } from "hono";
139-
import type { Context } from "hono";
140139
import { cache } from "hono/cache";
141140

142-
type Env = {
143-
// Cloudflare Worker environment
144-
};
145-
146141
const app = new Hono();
147142

148143
// We leverage hono built-in cache helper here

src/content/docs/workers/examples/geolocation-hello-world.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ const app = new Hono();
166166

167167
app.get("*", (c) => {
168168
// Cast the raw request to include Cloudflare-specific properties
169-
const request = c.req.raw as RequestWithCf;
169+
const request = c.req.raw;
170170

171171
// Define styles
172172
const html_style =

0 commit comments

Comments
 (0)