diff --git a/src/content/docs/workers/examples/alter-headers.mdx b/src/content/docs/workers/examples/alter-headers.mdx index f04da40ccc49445..33ed6af55674e80 100644 --- a/src/content/docs/workers/examples/alter-headers.mdx +++ b/src/content/docs/workers/examples/alter-headers.mdx @@ -90,7 +90,7 @@ async def on_fetch(request): # Add a custom header with a value new_headers["x-workers-hello"] = "Hello from Cloudflare Workers" - + # Delete headers if "x-header-to-delete" in new_headers: del new_headers["x-header-to-delete"] @@ -113,19 +113,19 @@ const app = new Hono(); app.use('*', async (c, next) => { // Process the request with the next middleware/handler await next(); - + // After the response is generated, we can modify its headers - + // Add a custom header with a value c.res.headers.append( "x-workers-hello", "Hello from Cloudflare Workers with Hono" ); - + // Delete headers c.res.headers.delete("x-header-to-delete"); c.res.headers.delete("x-header2-to-delete"); - + // Adjust the value for an existing header c.res.headers.set("x-header-to-change", "NewValue"); }); @@ -133,7 +133,7 @@ app.use('*', async (c, next) => { app.get('*', async (c) => { // Fetch content from example.com const response = await fetch("https://example.com"); - + // Return the response body with original headers // (our middleware will modify the headers before sending) return new Response(response.body, { diff --git a/src/content/docs/workers/examples/auth-with-headers.mdx b/src/content/docs/workers/examples/auth-with-headers.mdx index 121f1ff57f84681..f028f87a0822cd3 100644 --- a/src/content/docs/workers/examples/auth-with-headers.mdx +++ b/src/content/docs/workers/examples/auth-with-headers.mdx @@ -109,7 +109,7 @@ app.use('*', async (c, next) => { */ const PRESHARED_AUTH_HEADER_KEY = "X-Custom-PSK"; const PRESHARED_AUTH_HEADER_VALUE = "mypresharedkey"; - + // Get the pre-shared key from the request header const psk = c.req.header(PRESHARED_AUTH_HEADER_KEY); diff --git a/src/content/docs/workers/examples/cache-using-fetch.mdx b/src/content/docs/workers/examples/cache-using-fetch.mdx index e42e86d9106b6d6..e8cafe90e2ae0ff 100644 --- a/src/content/docs/workers/examples/cache-using-fetch.mdx +++ b/src/content/docs/workers/examples/cache-using-fetch.mdx @@ -87,11 +87,11 @@ const app = new Hono<{ Bindings: Bindings }>(); app.all('*', async (c) => { const url = new URL(c.req.url); - + // Only use the path for the cache key, removing query strings // and always store using HTTPS, for example, https://www.example.com/file-uri-here const someCustomKey = `https://${url.hostname}${url.pathname}`; - + // Fetch the request with custom cache settings let response = await fetch(c.req.raw, { cf: { @@ -103,13 +103,13 @@ app.all('*', async (c) => { cacheKey: someCustomKey, }, }); - + // Reconstruct the Response object to make its headers mutable response = new Response(response.body, response); - + // Set cache control headers to cache on browser for 25 minutes response.headers.set("Cache-Control", "max-age=1500"); - + return response; }); @@ -278,17 +278,17 @@ const app = new Hono<{ Bindings: Bindings }>(); app.all('*', async (c) => { const originalUrl = c.req.url; const url = new URL(originalUrl); - + // Randomly select a storage backend if (Math.random() < 0.5) { url.hostname = "example.s3.amazonaws.com"; } else { url.hostname = "example.storage.googleapis.com"; } - + // Create a new request to the selected backend const newRequest = new Request(url, c.req.raw); - + // Fetch using the original URL as the cache key return fetch(newRequest, { cf: { cacheKey: originalUrl }, diff --git a/src/content/docs/workers/examples/country-code-redirect.mdx b/src/content/docs/workers/examples/country-code-redirect.mdx index fe6b7da2794c8f3..aab79a55ab121cb 100644 --- a/src/content/docs/workers/examples/country-code-redirect.mdx +++ b/src/content/docs/workers/examples/country-code-redirect.mdx @@ -127,7 +127,7 @@ app.get('*', async (c) => { // Cast the raw request to include Cloudflare-specific properties const request = c.req.raw as RequestWithCf; - + // Use the cf object to obtain the country of the request // more on the cf object: https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties const country = request.cf.country; diff --git a/src/content/docs/workers/examples/cron-trigger.mdx b/src/content/docs/workers/examples/cron-trigger.mdx index 99084729e2d0355..3efa2e87c154bf7 100644 --- a/src/content/docs/workers/examples/cron-trigger.mdx +++ b/src/content/docs/workers/examples/cron-trigger.mdx @@ -49,7 +49,7 @@ app.get('/', (c) => c.text('Hello World!')); export default { // The Hono app handles regular HTTP requests fetch: app.fetch, - + // The scheduled function handles Cron triggers async scheduled( controller: ScheduledController, @@ -57,7 +57,7 @@ export default { ctx: ExecutionContext, ) { console.log("cron processed"); - + // You could also perform actions like: // - Fetching data from external APIs // - Updating KV or Durable Object storage diff --git a/src/content/docs/workers/examples/data-loss-prevention.mdx b/src/content/docs/workers/examples/data-loss-prevention.mdx index e7d6a3e1ac9e65d..c64c08aafd031d5 100644 --- a/src/content/docs/workers/examples/data-loss-prevention.mdx +++ b/src/content/docs/workers/examples/data-loss-prevention.mdx @@ -258,30 +258,30 @@ async function postDataBreach(request: Request) { app.use('*', async (c) => { // Fetch the origin response const response = await fetch(c.req.raw); - + // Return origin response if response wasn't text const contentType = response.headers.get("content-type") || ""; if (!contentType.toLowerCase().includes("text/")) { return response; } - + // Get the response text let text = await response.text(); - + // When debugging, replace the response from the origin with an email text = DEBUG ? text.replace("You may use this", "me@example.com may use this") : text; - + // Check for sensitive data for (const kind in sensitiveRegexsMap) { const sensitiveRegex = new RegExp(sensitiveRegexsMap[kind], "ig"); const match = sensitiveRegex.test(text); - + if (match) { // Alert a data breach await postDataBreach(c.req.raw); - + // Respond with a block if credit card, otherwise replace sensitive text with `*`s if (kind === "creditCard") { return c.text(`${kind} found\nForbidden\n`, 403); @@ -294,7 +294,7 @@ app.use('*', async (c) => { } } } - + // Return the modified response return new Response(text, { status: response.status, diff --git a/src/content/docs/workers/examples/debugging-logs.mdx b/src/content/docs/workers/examples/debugging-logs.mdx index d706124f7ba1225..234fe35cfac1c6f 100644 --- a/src/content/docs/workers/examples/debugging-logs.mdx +++ b/src/content/docs/workers/examples/debugging-logs.mdx @@ -168,7 +168,7 @@ app.use('*', async (c, next) => { try { // Process the request with the next handler await next(); - + // After processing, check if the response indicates an error if (c.res && (!c.res.ok && !c.res.redirected)) { const body = await c.res.clone().text(); @@ -180,28 +180,28 @@ app.use('*', async (c, next) => { body.trim().substring(0, 10) ); } - + } catch (err) { // Without waitUntil, the fetch to the logging service may not complete c.executionCtx.waitUntil( postLog(err.toString()) ); - + // Get the error stack or error itself const stack = JSON.stringify(err.stack) || err.toString(); - + // Create a new response with the error information - const response = c.res ? + const response = c.res ? new Response(stack, { status: c.res.status, headers: c.res.headers - }) : + }) : new Response(stack, { status: 500 }); - + // Add debug headers response.headers.set("X-Debug-stack", stack); response.headers.set("X-Debug-err", err.toString()); - + // Set the modified response c.res = response; } diff --git a/src/content/docs/workers/examples/extract-cookie-value.mdx b/src/content/docs/workers/examples/extract-cookie-value.mdx index e7ca1c827b34c34..435761c5d22eccc 100644 --- a/src/content/docs/workers/examples/extract-cookie-value.mdx +++ b/src/content/docs/workers/examples/extract-cookie-value.mdx @@ -84,15 +84,15 @@ const app = new Hono(); app.get('*', (c) => { // The name of the cookie const COOKIE_NAME = "__uid"; - + // Get the specific cookie value using Hono's cookie helper const cookieValue = getCookie(c, COOKIE_NAME); - + if (cookieValue) { // Respond with the cookie value return c.text(cookieValue); } - + return c.text("No cookie with name: " + COOKIE_NAME); }); diff --git a/src/content/docs/workers/examples/fetch-json.mdx b/src/content/docs/workers/examples/fetch-json.mdx index fbfdd541d4f5e22..4f7f9d64bbffd3c 100644 --- a/src/content/docs/workers/examples/fetch-json.mdx +++ b/src/content/docs/workers/examples/fetch-json.mdx @@ -113,11 +113,11 @@ app.get('*', async (c) => { async function gatherResponse(response: Response) { const { headers } = response; const contentType = headers.get("content-type") || ""; - + if (contentType.includes("application/json")) { return { contentType, result: JSON.stringify(await response.json()) }; } - + return { contentType, result: await response.text() }; } diff --git a/src/content/docs/workers/examples/geolocation-app-weather.mdx b/src/content/docs/workers/examples/geolocation-app-weather.mdx index ef190d1c3f5b68c..d752396fc245c89 100644 --- a/src/content/docs/workers/examples/geolocation-app-weather.mdx +++ b/src/content/docs/workers/examples/geolocation-app-weather.mdx @@ -149,18 +149,18 @@ app.get('*', async (c) => { // Get API endpoint let endpoint = "https://api.waqi.info/feed/geo:"; const token = ""; // Use a token from https://aqicn.org/api/ - + // Define styles const html_style = `body{padding:6em; font-family: sans-serif;} h1{color:#f6821f}`; - + // Get geolocation from Cloudflare request const req = c.req.raw; const latitude = req.cf?.latitude; const longitude = req.cf?.longitude; - + // Create complete API endpoint with coordinates endpoint += `${latitude};${longitude}/?token=${token}`; - + // Fetch weather data const init = { headers: { @@ -169,7 +169,7 @@ app.get('*', async (c) => { }; const response = await fetch(endpoint, init); const content = await response.json() as WeatherApiResponse; - + // Build HTML content const weatherContent = html`
The O3 level is: ${content.data.iaqi.o3?.v}.
The temperature is: ${content.data.iaqi.t?.v}°C.
`; - + // Complete HTML document const htmlDocument = html` @@ -195,7 +195,7 @@ app.get('*', async (c) => {