### Hono Basic Example Source: https://hono.dev/ A simple 'Hello Hono!' example demonstrating how to create a basic Hono application and define a GET route for the root path. This snippet showcases the core functionality of setting up a server response. ```JavaScript import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Hono!')) export default app ``` -------------------------------- ### Deploy Hono with Cloudflare Workers Source: https://developers.cloudflare.com/llms.txt This guide details how to deploy a Hono application with Cloudflare Workers. Hono is a fast, minimalist web framework for the edge. ```javascript import { Hono } from 'hono'; const app = new Hono(); app.get('/', (c) => { return c.text('Hello Hono!'); }); export default { fetch: app.fetch, }; ``` -------------------------------- ### Hono Framework Cloudflare Workers AI App with Streaming Source: https://github.com/craigsdennis/hackathon-helper-workers-ai This example showcases the integration of the Hono framework with Cloudflare Workers AI, including advanced streaming examples. Hono is a lightweight web framework that enhances performance and developer experience. ```JavaScript import { Hono } from 'hono' import { stream } from 'hono/streaming' const app = new Hono() app.get('/', (c) => { return c.body('Hello Hono!') }) app.post('/stream', async (c) => { const body = await c.req.json() const prompt = body.prompt const streamResponse = await c.env.AI.run( '@cf/meta/llama-2-7b-chat-fp16', { prompt: prompt }, { stream: true } ) return stream(c, async (stream) => { for await (const chunk of streamResponse.toIterable()) { await stream.write(chunk.response) } }) }) export default app; ``` -------------------------------- ### Hono Rate Limiter Middleware Setup Source: https://github.com/rhinobase/hono-rate-limiter This snippet demonstrates how to set up and use the Hono Rate Limiter middleware in a Hono Server application. It outlines the basic configuration required to protect your API endpoints from excessive requests. ```typescript import { Hono } from 'hono'; import { rateLimiter } from '@hono/rate-limiter'; const app = new Hono(); // Apply rate limiter to all routes app.use(rateLimiter({ windowMs: 15 * 60 * 1000, // 15 minutes limit: 100, // limit each IP to 100 requests per windowMs })); // Example route app.get('/', (c) => { return c.text('Hello Hono!'); }); export default app; ``` -------------------------------- ### Install Hono Rate Limiter via npm Source: https://github.com/rhinobase/hono-rate-limiter This snippet shows how to install the hono-rate-limiter package using npm. It's a common first step for integrating rate limiting into a Hono application. ```bash npm install hono-rate-limiter ``` -------------------------------- ### Hono API Reference for App Source: https://hono.dev/docs/getting-started/cloudflare-workers Documentation for the core Hono App API, which is the foundation for building web applications with Hono. Covers initialization and basic routing. ```markdown /docs/api/hono ``` -------------------------------- ### Proxy requests based on hostname with Hono Source: https://context7_llms This Hono code snippet implements a proxy that redirects requests to different origins based on the hostname. It utilizes the `hono/proxy` middleware and a mapping object to determine the target origin. Requests matching a key in the `ORIGINS` object are proxied to the corresponding value; otherwise, they are proxied to the original request. ```typescript import { Hono } from "hono"; import { proxy } from "hono/proxy"; // An object with different URLs to fetch const ORIGINS: Record = { "starwarsapi.yourdomain.com": "swapi.dev", "google.yourdomain.com": "www.google.com", }; const app = new Hono(); app.all("*", async (c) => { const url = new URL(c.req.url); // Check if incoming hostname is a key in the ORIGINS object if (url.hostname in ORIGINS) { const target = ORIGINS[url.hostname]; url.hostname = target; // If it is, proxy request to that third party origin return proxy(url, c.req.raw); } // Otherwise, process request as normal return proxy(c.req.raw); }); export default app; ``` -------------------------------- ### Hono 'Hello World' Example Source: https://hono.dev/docs/getting-started/cloudflare-workers A basic 'Hello World' example for a Cloudflare Worker using Hono in TypeScript. It sets up a Hono application and defines a route that returns 'Hello Cloudflare Workers!' for the root path. ```TypeScript import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Cloudflare Workers!')) export default app ``` -------------------------------- ### Hono Getting Started with Deno Source: https://hono.dev/docs/getting-started/cloudflare-workers Instructions for using Hono with the Deno runtime. This guide explains how to leverage Hono's features within the Deno ecosystem. ```markdown /docs/getting-started/deno ``` -------------------------------- ### Basic Hono Application for Testing Source: https://hono.dev/docs/getting-started/cloudflare-workers A simple Hono application that responds with 'Please test me!' to root requests, suitable for testing. ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Please test me!')) ``` -------------------------------- ### Hono Getting Started with Bun Source: https://hono.dev/docs/getting-started/cloudflare-workers Learn how to integrate Hono with the Bun runtime. This guide provides steps for setting up and running Hono applications using Bun. ```markdown /docs/getting-started/bun ``` -------------------------------- ### Install Hono Framework (npm) Source: https://context7_llms Install the Hono framework, a lightweight web framework for Cloudflare Workers, using npm. Hono simplifies the process of defining routes and middleware for your Worker application. ```sh npm i hono ``` -------------------------------- ### Install hono-rate-limiter Source: https://github.com/rhinobase/hono-rate-limiter This snippet shows how to install the 'hono-rate-limiter' package using npm, yarn, pnpm, or bun. It's a prerequisite for using the rate limiting functionality in your Hono application. ```shell # Using npm/yarn/pnpm/bun npm add hono-rate-limiter ``` -------------------------------- ### Hono Guides on Best Practices Source: https://hono.dev/docs/getting-started/cloudflare-workers Recommendations and best practices for building efficient, maintainable, and scalable applications with Hono. ```markdown /docs/best-practices ``` -------------------------------- ### TypeScript Hotlink Protection (Hono) Source: https://developers.cloudflare.com/workers/examples/hot-link-protection/ Demonstrates hotlink protection using Hono in TypeScript for Cloudflare Workers. It includes middleware to intercept requests, check referrers for images, and perform redirects. ```typescript import { Hono } from 'hono'; const app = new Hono(); // Middleware for hot-link protection app.use('*', async (c, next) => { const HOMEPAGE_URL = "https://tutorial.cloudflareworkers.com/"; const PROTECTED_TYPE = "image/"; // Continue to the next handler to get the response await next(); // If we have a response, check for hotlinking if (c.res) { // If it's an image, engage hotlink protection based on the Referer header const referer = c.req.header("Referer"); const contentType = c.res.headers.get("Content-Type") || ""; if (referer && contentType.startsWith(PROTECTED_TYPE)) { // If the hostnames don't match, it's a hotlink if (new URL(referer).hostname !== new URL(c.req.url).hostname) { // Redirect the user to your website c.res = c.redirect(HOMEPAGE_URL, 302); } } } }); // Default route handler that passes through the request to the origin app.all('*', async (c) => { // Fetch the original request return fetch(c.req.raw); }); export default app; ``` -------------------------------- ### Hono Multiple Cron Triggers Source: https://context7_llms This Hono example integrates multiple Cron Triggers with a Hono application for Cloudflare Workers. It exports both the Hono app for HTTP requests and a `scheduled` function that handles cron events, using a switch statement to differentiate between schedules. ```typescript import { Hono } from "hono"; interface Env {} // Create Hono app const app = new Hono<{ Bindings: Env }>(); // Regular routes for normal HTTP requests app.get("/", (c) => c.text("Multiple Cron Trigger Example")); // Export both the app and a scheduled function export default { // The Hono app handles regular HTTP requests fetch: app.fetch, // The scheduled function handles Cron triggers async scheduled( controller: ScheduledController, env: Env, ctx: ExecutionContext, ) { ``` ```typescript // Check which cron schedule triggered this execution switch (controller.cron) { case "*/3 * * * *": ``` ```typescript // Every three minutes await updateAPI(); break; case "*/10 * * * *": ``` ```typescript // Every ten minutes await updateAPI2(); break; case "*/45 * * * *": ``` ```typescript // Every forty-five minutes await updateAPI3(); break; } console.log("cron processed"); }, }; ``` -------------------------------- ### TypeScript Hono API for Streaming with Cloudflare Workers Source: https://github.com/craigsdennis/hackathon-helper-workers-ai A TypeScript-based API using the Hono framework for Cloudflare Workers, demonstrating streaming capabilities for both the server and client. This provides a robust solution for real-time AI interactions. ```TypeScript import { Hono } from 'hono'; import { stream } from 'hono/streaming'; interface Env { AI: any; } const app = new Hono(); app.post('/stream-ts', async (c) => { const prompt = await c.req.json<{ prompt: string }>(); const aiResponse = await c.env.AI.run("@cf/meta/llama-2-7b-chat-int8", { "prompt": prompt.prompt }); return stream(c, async (stream) => { for await (const chunk of aiResponse.toIterable()) { stream.write(chunk); } }); }); export default app; ``` -------------------------------- ### Implement WebSocket Rate Limiting with Redis Source: https://github.com/rhinobase/hono-rate-limiter This snippet shows how to apply rate limiting to WebSocket requests using the `hono-rate-limiter` middleware with a Redis store. It configures the limiter with a specific window, limit, and a custom key generator, and integrates it with Hono's `upgradeWebSocket` function. ```javascript import { webSocketLimiter } from "hono-rate-limiter"; import { upgradeWebSocket } from "hono/cloudflare-workers"; import { RedisStore } from "@hono-rate-limiter/redis"; import { Redis } from "@upstash/redis/cloudflare"; const limiter = webSocketLimiter({ windowMs: 15 * 60 * 1000, // 15 minutes limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes). keyGenerator: (c) => "", // Method to generate custom identifiers for clients. store: new RedisStore({ client }), // Define your DataStore. See below. }); // Apply the rate limiting middleware to ws requests. app.get( "/", upgradeWebSocket( limiter((c) => { return { onOpen: () => { console.log("Connection opened"); }, async onMessage(event, ws) { console.log(`Message from client: ${event.data}`); ws.send("Hello from server!"); }, onClose: () => { console.log("Connection closed"); }, }; }) ) ); ``` -------------------------------- ### Install Hono Rate Limiter Source: https://github.com/rhinobase/hono-rate-limiter Instructions for installing the hono-rate-limiter package using various package managers like npm, yarn, pnpm, and bun. ```bash npm add hono-rate-limiter ``` -------------------------------- ### Read Cookie in Hono Source: https://context7_llms Shows how to access a specific cookie value (__uid) from a request using the Hono framework. It leverages Hono's `getCookie` utility for easy cookie retrieval. ```TypeScript import { Hono } from 'hono'; import { getCookie } from 'hono/cookie'; 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); }); export default app; ``` -------------------------------- ### Redirect all requests to one URL - Hono Source: https://developers.cloudflare.com/workers/examples/redirect/ Redirects all incoming requests to a specified destination URL with a 301 status code using the Hono framework. Hono simplifies routing and response handling. ```JavaScript import { Hono } from "hono"; const app = new Hono(); app.all("*", (c) => { const destinationURL = "https://example.com"; const statusCode = 301; return c.redirect(destinationURL, statusCode); }); export default app; ``` -------------------------------- ### Hono Bulk Redirects Source: https://context7_llms Demonstrates bulk redirects using the Hono framework in TypeScript. It sets up middleware to intercept requests, check against a redirect map, and perform 301 redirects or pass requests to the next handler. ```typescript import { Hono } from "hono"; const app = new Hono(); // Configure your redirects const externalHostname = "examples.cloudflareworkers.com"; const redirectMap = new Map([ ["/bulk1", `https://${externalHostname}/redirect2`], ["/bulk2", `https://${externalHostname}/redirect3`], ["/bulk3", `https://${externalHostname}/redirect4`], ["/bulk4", "https://google.com"], ]); // Middleware to handle redirects app.use("*", async (c, next) => { const path = c.req.path; const location = redirectMap.get(path); if (location) { // If path is in our redirect map, perform the redirect return c.redirect(location, 301); } // Otherwise, continue to the next handler await next(); }); // Default handler for requests that don't match any redirects app.all("*", async (c) => { // Pass through to origin return fetch(c.req.raw); }); export default app; ``` -------------------------------- ### Hono: Conditional Response Example Source: https://developers.cloudflare.com/workers/examples/conditional-response/ This Hono example for Cloudflare Workers showcases conditional responses using the Hono framework. It highlights how to define routes and middleware to handle different request conditions efficiently. -------------------------------- ### Apply Rate Limiter Middleware to Hono App Source: https://github.com/rhinobase/hono-rate-limiter Demonstrates how to apply the rateLimiter middleware to all requests in a Hono application. It includes configuration options such as windowMs, limit, standardHeaders, and keyGenerator. ```javascript import { rateLimiter } from "hono-rate-limiter"; // Apply the rate limiting middleware to all requests. app.use( rateLimiter({ windowMs: 15 * 60 * 1000, // 15 minutes limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes). standardHeaders: "draft-6", // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header keyGenerator: (c) => "", // Method to generate custom identifiers for clients. // store: ... , // Redis, MemoryStore, etc. See below. }) ); ``` -------------------------------- ### Basic Hono Application Structure Source: https://context7_llms This TypeScript code defines a minimal Hono application. It sets up a basic route that responds to GET requests on the root path with 'Hello Hono!'. Any other path or method will result in a 404 Not Found. ```typescript import { Hono } from "hono"; type Bindings = { [key in keyof CloudflareBindings]: CloudflareBindings[key]; }; const app = new Hono<{ Bindings: Bindings }>(); app.get("/", (c) => { return c.text("Hello Hono!"); }); export default app; ``` -------------------------------- ### Install Hono Framework (yarn) Source: https://context7_llms Install the Hono framework using yarn. Hono is a fast and flexible web framework designed for building Cloudflare Workers applications efficiently. ```sh yarn add hono ``` -------------------------------- ### Initialize Hono App Source: https://context7_llms Initializes a new Hono application instance. Hono is a web framework that excels at running on Cloudflare Workers. ```TypeScript import { Hono } from "hono"; const app = new Hono(); export default app; ``` -------------------------------- ### Hono Framework Overview Source: https://hono.dev/ This section provides a high-level overview of the Hono web framework, highlighting its core concepts such as motivation, routers, benchmarks, adherence to web standards, middleware, developer experience, and Hono Stacks. ```markdown Concepts Motivation Routers Benchmarks Web Standard Middleware Developer Experience Hono Stacks Getting Started Basic Cloudflare Workers Cloudflare Pages Deno Bun Fastly Compute ``` -------------------------------- ### Hono Guides on RPC Source: https://hono.dev/docs/getting-started/cloudflare-workers Documentation on using Remote Procedure Calls (RPC) with Hono, enabling communication between client and server. ```markdown /docs/guides/rpc ``` -------------------------------- ### Hono Basic App Setup Source: https://developers.cloudflare.com/workers/tutorials/build-a-slackbot/ A minimal Hono application that responds to GET requests on the root path with 'Hello Hono!'. It returns a 404 for any other path or method. ```typescript import { Hono } from "hono"; type Bindings = { [key in keyof CloudflareBindings]: CloudflareBindings[key];}; const app = new Hono<{ Bindings: Bindings }>(); app.get("/", (c) => { return c.text("Hello Hono!");}); export default app; ``` -------------------------------- ### Wrangler Configuration for Hono Project Source: https://hono.dev/docs/getting-started/cloudflare-workers This TOML snippet configures the `wrangler.toml` file for a Hono project. It specifies the main entry point of the application (`src/index.ts`) and enables minification for the deployed code. ```toml main = "src/index.ts" minify = true ``` -------------------------------- ### Aggregate Responses with Hono Source: https://developers.cloudflare.com/workers/examples/aggregate-requests/ This example uses the Hono framework to aggregate responses from two URLs. It sets up a Hono application and defines a fetch handler that makes concurrent requests to two JSON endpoints, processes the results, and returns them. ```JavaScript import { Hono } from "hono"; const app = new Hono(); // Placeholder for Hono implementation // Actual aggregation logic would go here, similar to the JS/TS examples. ``` -------------------------------- ### Hono API Reference for Presets Source: https://hono.dev/docs/getting-started/cloudflare-workers Details on Hono's preset configurations and how they can be used to quickly set up common application patterns. ```markdown /docs/api/presets ``` -------------------------------- ### JavaScript Hono Integration with Cloudflare Workers Source: https://developers.cloudflare.com/workers/framework-guides/ Guide for building web applications using the Hono framework on Cloudflare Workers. Hono is a lightweight web framework for Cloudflare Workers, Deno, and Bun, known for its performance and minimalist design. ```javascript // Example of a basic Hono application for Cloudflare Workers import { Hono } from 'hono'; const app = new Hono(); // Define a route for the root path app.get('/', (c) => { return c.text('Hello from Hono on Cloudflare Workers!'); }); // Define another route with a parameter app.get('/greet/:name', (c) => { const name = c.req.param('name'); return c.text(`Hello, ${name}!`); }); // Export the Hono app as the Cloudflare Worker handler export default { fetch: app.fetch, }; // To run this locally or deploy, you would typically use: // 1. wrangler CLI: `wrangler dev` or `wrangler publish` // 2. Or configure it as the 'fetch' handler in your worker's index file. ``` -------------------------------- ### Hono Guides on Helpers Source: https://hono.dev/docs/getting-started/cloudflare-workers Documentation on Hono's built-in helpers and utilities that simplify common web development tasks. ```markdown /docs/guides/helpers ``` -------------------------------- ### Hono Guides on Middleware Source: https://hono.dev/docs/getting-started/cloudflare-workers A guide to creating and using middleware in Hono for tasks like authentication, logging, and request modification. ```markdown /docs/guides/middleware ``` -------------------------------- ### Query D1 from Hono Source: https://developers.cloudflare.com/llms.txt Demonstrates how to query a D1 database from within a Hono web framework application. This example focuses on the integration between D1 and Hono for data access. ```javascript import { Hono } from 'hono' import { D1Database } from '@cloudflare/workers-types/d1' const app = new Hono() app.get('/posts', async (c) => { const db = c.env.DB as D1Database const { results } = await db.prepare('SELECT * FROM posts').all() return c.json({ posts: results }) }) export default app ``` -------------------------------- ### Hono API Reference for Context Source: https://hono.dev/docs/getting-started/cloudflare-workers Explanation of the request context object in Hono, which provides access to request details, response methods, and other utilities. ```markdown /docs/api/context ``` -------------------------------- ### Hono Rate Limiter with Redis Store Source: https://github.com/rhinobase/hono-rate-limiter Example of configuring the hono-rate-limiter with a Redis store, demonstrating how to handle potential TypeScript type issues by casting the store. ```typescript import { RedisStore } from '@hono-rate-limiter/redis'; import { rateLimiter } from '@hono-rate-limiter/core'; // Assuming redisClient is an initialized Redis client // const redisClient = new Redis(...); rateLimiter({ // ... other options store: new RedisStore({ sendCommand: (...args: string[]) => redisClient.sendCommand(args), }) as unknown as Store, }); ``` -------------------------------- ### Create Hono App with Cron Trigger Source: https://developers.cloudflare.com/workers/examples/multiple-cron-triggers/ This code snippet demonstrates how to create a Hono app with a basic route. It defines a simple HTTP endpoint that returns a text response. Hono is used to create a lightweight web application. ```Hono import { Hono } from "hono"; interface Env {} // Create Hono appconst app = new Hono<{ Bindings: Env }>(); // Regular routes for normal HTTP requestsapp.get("/", (c) => c.text("Multiple Cron Trigger Example")); ``` -------------------------------- ### Install Hono Rate Limiter via JSR Source: https://github.com/rhinobase/hono-rate-limiter This snippet demonstrates how to install the hono-rate-limiter package using JSR. JSR is a package registry for JavaScript and TypeScript. ```bash jsr add hono-rate-limiter ``` -------------------------------- ### Hono App for Dynamic HTML with Time and Gradient (TypeScript) Source: https://context7_llms This TypeScript code uses the Hono framework to create a web application. It defines gradient configurations for different hours and generates an HTML response displaying the current time and timezone with a corresponding background gradient. This approach leverages Hono's routing and middleware capabilities. ```typescript import { Hono } from 'hono'; type Bindings = {}; type ColorStop = { color: string; position: number }; const app = new Hono<{ Bindings: Bindings }>(); // Gradient configurations for each hour of the day (0-23) const grads: ColorStop[][] = [ [ { color: "00000c", position: 0 }, { color: "00000c", position: 0 }, ], [ { color: "020111", position: 85 }, { color: "191621", position: 100 }, ], [ { color: "020111", position: 60 }, { color: "20202c", position: 100 }, ], [ { color: "020111", position: 10 }, { color: "3a3a52", position: 100 }, ], [ { color: "20202c", position: 0 }, { color: "515175", position: 100 }, ], [ { color: "40405c", position: 0 }, { color: "6f71aa", position: 80 }, { color: "8a76ab", position: 100 }, ], [ { color: "4a4969", position: 0 }, { color: "7072ab", position: 50 }, { color: "cd82a0", position: 100 }, ], [ { color: "757abf", position: 0 }, { color: "8583be", position: 60 }, { color: "eab0d1", position: 100 }, ], [ { color: "82addb", position: 0 }, { color: "ebb2b1", position: 100 }, ], [ { color: "94c5f8", position: 1 }, { color: "a6e6ff", position: 70 }, { color: "b1b5ea", position: 100 }, ], [ { color: "b7eaff", position: 0 }, { color: "94dfff", position: 100 }, ], [ { color: "9be2fe", position: 0 }, { color: "67d1fb", position: 100 }, ], [ { color: "90dffe", position: 0 }, { color: "38a3d1", position: 100 }, ], [ { color: "57c1eb", position: 0 }, { color: "246fa8", position: 100 }, ], [ { color: "2d91c2", position: 0 }, { color: "1e528e", position: 100 }, ], [ { color: "2473ab", position: 0 }, { color: "1e528e", position: 70 }, { color: "5b7983", position: 100 }, ], [ { color: "1e528e", position: 0 }, { color: "265889", position: 50 }, { color: "9da671", position: 100 }, ], [ { color: "1e528e", position: 0 }, { color: "728a7c", position: 50 }, { color: "e9ce5d", position: 100 }, ], [ { color: "154277", position: 0 }, { color: "576e71", position: 30 }, { color: "e1c45e", position: 70 }, { color: "b26339", position: 100 }, ], [ { color: "163C52", position: 0 }, { color: "4F4F47", position: 30 }, { color: "C5752D", position: 60 }, { color: "B7490F", position: 80 }, { color: "2F1107", position: 100 }, ], [ { color: "071B26", position: 0 }, { color: "071B26", position: 30 }, { color: "8A3B12", position: 80 }, { color: "240E03", position: 100 }, ], [ ``` -------------------------------- ### Hono Cache Middleware Source: https://context7_llms Utilizes Hono's built-in cache middleware for efficient caching. This example sets a cache name and a cache control directive (max-age=3600) for all routes, simplifying cache management within the Hono framework. ```TypeScript import { Hono } from "hono"; import { cache } from "hono/cache"; const app = new Hono(); // We leverage hono built-in cache helper here app.get( "*", cache({ cacheName: "my-cache", cacheControl: "max-age=3600", // 1 hour }), ); // Add a route to handle the request if it's not in cache app.get("*", (c) => { return c.text("Hello from Hono!"); }); export default app; ``` -------------------------------- ### Hono Client Setup for React Hydration (TypeScript) Source: https://github.com/honojs/honox Configures the Hono client-side JavaScript to hydrate React components. It defines how to create elements and hydrate the root using `react-dom/client`. ```typescript // app/client.ts import { createClient } from 'honox/client' createClient({ hydrate: async (elem, root) => { const { hydrateRoot } = await import('react-dom/client') hydrateRoot(root, elem) }, createElement: async (type: any, props: any) => { const { createElement } = await import('react') return createElement(type, props) }, }) ``` -------------------------------- ### Install Hono Framework Source: https://developers.cloudflare.com/d1/tutorials/build-an-api-to-access-d1/ Instructions to install the Hono framework, an Express.js-style framework for building APIs, using npm, yarn, or pnpm. Hono is used for routing and handling requests. ```bash npm i hono ``` ```bash yarn add hono ``` ```bash pnpm add hono ``` -------------------------------- ### Test Hono Application Response Source: https://hono.dev/docs/getting-started/cloudflare-workers Vitest code to test a Hono application, verifying that a request to the root path returns a 200 OK response. ```ts describe('Test the application', () => { it('Should return 200 response', async () => { const res = await app.request('http://localhost/') expect(res.status).toBe(200) }) }) ``` -------------------------------- ### Hono: Sensitive Data Detection and Redaction Source: https://context7_llms This Hono (TypeScript) example sets up a web application that processes requests. It defines regular expressions to identify sensitive data like credit cards, emails, and phone numbers. The code includes a function to post data breach alerts and handles responses based on the detected sensitive information, redacting it or returning a forbidden status for credit cards. ```typescript import { Hono } from 'hono'; const app = new Hono(); // Configuration const DEBUG = true; const SOME_HOOK_SERVER = "https://webhook.flow-wolf.io/hook"; // Define sensitive data patterns const sensitiveRegexsMap = { creditCard: String.raw`\b(?:4[0-9]{12}(?:[0-9]{3})?|(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})\b`, email: String.raw`\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b`, phone: String.raw`\b07\d{9}\b`, }; /** * Alert a data breach by posting to a webhook server */ async function postDataBreach(request: Request) { return await fetch(SOME_HOOK_SERVER, { method: "POST", headers: { "content-type": "application/json;charset=UTF-8", }, body: JSON.stringify({ ip: request.headers.get("cf-connecting-ip"), time: Date.now(), request: request, }), }); } ``` -------------------------------- ### Install Dependencies for Hono App Source: https://hono.dev/docs/getting-started/cloudflare-workers Commands to install project dependencies after creating a Hono application, using npm, yarn, pnpm, or bun. ```Shell cd my-app npm i ``` ```Shell cd my-app yarn ``` ```Shell cd my-app pnpm i ``` ```Shell cd my-app bun i ``` -------------------------------- ### Hono Module Worker with Scheduled Event Source: https://hono.dev/docs/getting-started/cloudflare-workers Example of integrating Hono with other event handlers like 'scheduled' in Module Worker mode. Exports `app.fetch` as the module's fetch handler. ```ts import { Hono } from 'hono' const app = new Hono() export default { fetch: app.fetch, scheduled: async (batch, env) => {}, } ``` -------------------------------- ### Cache POST Requests with Hono and SHA-256 Hashing Source: https://context7_llms This Hono middleware example shows how to cache POST requests. It utilizes the `hono/utils/crypto` module for SHA-256 hashing of the request body. The middleware constructs a cache key by appending the hash to the URL's pathname and attempts to serve responses from the cache before falling back to fetching from the origin. ```typescript import { Hono } from "hono"; import { sha256 } from "hono/utils/crypto"; const app = new Hono(); // Middleware for caching POST requests app.post("*", async (c) => { try { // Get the request body const body = await c.req.raw.clone().text(); // Hash the request body to use it as part of the cache key const hash = await sha256(body); // Create the cache URL const cacheUrl = new URL(c.req.url); // Store the URL in cache by prepending the body's hash cacheUrl.pathname = "/posts" + cacheUrl.pathname + hash; // Convert to a GET to be able to cache const cacheKey = new Request(cacheUrl.toString(), { headers: c.req.raw.headers, method: "GET", }); const cache = caches.default; ``` -------------------------------- ### Initialize Hono App with Bindings for Webhook Route Source: https://context7_llms This TypeScript code snippet shows how to initialize a Hono application for a webhook route. It includes the necessary import for Hono and the Bindings type, and correctly passes the Bindings generic to the Hono constructor, which is crucial for typing Slack webhook URLs. ```TypeScript import { Hono } from "hono"; import { Bindings } from "../types"; const app = new Hono<{ Bindings: Bindings }>(); export default app; ``` -------------------------------- ### Hono Getting Started with Cloudflare Workers Source: https://hono.dev/docs/getting-started/cloudflare-workers Guide to setting up and running Hono applications on Cloudflare Workers. This covers the basic steps to deploy a Hono app in a serverless environment. ```markdown /docs/getting-started/cloudflare-workers ``` -------------------------------- ### Hono Worker for JSON Requests Source: https://context7_llms This Hono (TypeScript) example sets up a basic web server that handles GET requests. It demonstrates making a POST request to an external API with JSON data and processing the response using a `gatherResponse` function. The response includes the content type and the processed result. ```typescript import { Hono } from 'hono'; const app = new Hono(); app.get('*', async (c) => { const someHost = "https://examples.cloudflareworkers.com/demos"; const url = someHost + "/requests/json"; const body = { results: ["default data to send"], errors: null, msg: "I sent this to the fetch", }; 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()) }; ``` -------------------------------- ### Install Hono with npm Source: https://developers.cloudflare.com/d1/tutorials/build-a-comments-api/ Installs the Hono framework, an Express.js-style framework for building APIs, using npm. This command is used to add Hono as a project dependency. ```Shell npm i hono ``` -------------------------------- ### Hono Getting Started with Node.js Source: https://hono.dev/docs/getting-started/cloudflare-workers Instructions for running Hono applications within a Node.js environment. This guide covers setup and basic usage. ```markdown /docs/getting-started/nodejs ``` -------------------------------- ### Hono Bindings with R2Bucket and Environment Variables Source: https://hono.dev/docs/getting-started/cloudflare-workers Example of using Hono with type-safe bindings for R2 Buckets and environment variables like USERNAME and PASSWORD. ```ts type Bindings = { MY_BUCKET: R2Bucket USERNAME: string PASSWORD: string } const app = new Hono<{ Bindings: Bindings }>() // Access to environment values app.put('/upload/:key', async (c, next) => { const key = c.req.param('key') await c.env.MY_BUCKET.put(key, c.req.body) return c.text(`Put ${key} successfully!`) }) ``` -------------------------------- ### Hono Getting Started with Fastly Compute Source: https://hono.dev/docs/getting-started/cloudflare-workers This guide details how to deploy and run Hono applications on the Fastly Compute@Edge platform, optimizing for edge computing. ```markdown /docs/getting-started/fastly ``` -------------------------------- ### Hono Guides on JSX Source: https://hono.dev/docs/getting-started/cloudflare-workers Learn how to use JSX with Hono for rendering HTML on the server or client-side. ```markdown /docs/guides/jsx ``` -------------------------------- ### Install Hono React Renderer Dependencies Source: https://github.com/honojs/honox Installs the necessary packages for using the Hono React renderer, including React, ReactDOM, Hono, and their corresponding TypeScript types. ```bash npm i @hono/react-renderer react react-dom hono npm i -D @types/react @types/react-dom ``` -------------------------------- ### Implement Hotlink Protection for Images using Hono Framework (TypeScript) Source: https://context7_llms This TypeScript example uses the Hono framework to implement hotlink protection for images within Cloudflare Workers. It defines middleware to intercept requests, checks the 'Referer' header for image content, and redirects hotlinked requests to a homepage. It also includes a default route handler to pass through requests. ```typescript import { Hono } from 'hono'; const app = new Hono(); // Middleware for hot-link protection app.use('*', async (c, next) => { const HOMEPAGE_URL = "https://tutorial.cloudflareworkers.com/"; const PROTECTED_TYPE = "image/"; // Continue to the next handler to get the response await next(); // If we have a response, check for hotlinking if (c.res) { // If it's an image, engage hotlink protection based on the Referer header const referer = c.req.header("Referer"); const contentType = c.res.headers.get("Content-Type") || ""; if (referer && contentType.startsWith(PROTECTED_TYPE)) { // If the hostnames don't match, it's a hotlink if (new URL(referer).hostname !== new URL(c.req.url).hostname) { // Redirect the user to your website c.res = c.redirect(HOMEPAGE_URL, 302); } } } }); // Default route handler that passes through the request to the origin app.all('*', async (c) => { // Fetch the original request return fetch(c.req.raw); }); export default app; ``` -------------------------------- ### Fetch and Process API Response in Hono Source: https://context7_llms Fetches data from a specified URL and processes the response using Hono, handling both JSON and text content types. It returns a new Response object with the processed content. ```TypeScript import { Hono } from 'hono'; type Env = {}; const app = new Hono<{ Bindings: Env }>(); app.get('*', async (c) => { const url = "https://jsonplaceholder.typicode.com/todos/1"; // gatherResponse returns both content-type & response body as a string 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() }; } const response = await fetch(url); const { contentType, result } = await gatherResponse(response); return new Response(result, { headers: { "content-type": contentType } }); }); export default app; ```