{
+ try {
+ if (!c.env?.ASSETS) {
+ throw new Error("ASSETS binding is not configured");
+ }
+
+ const imageUrl = new URL(imagePath, c.req.url).toString();
+ const imageData = await c.env.ASSETS.fetch(imageUrl);
+
+ // Get content-type from response
+ const contentType = imageData.headers.get("content-type") || "image/png";
+
+ const arrayBuffer = await imageData.arrayBuffer();
+ const base64Image = Buffer.from(arrayBuffer).toString("base64");
+ return `data:${contentType};base64,${base64Image}`;
+ } catch (error) {
+ console.warn(`Failed to load image ${imagePath}:`, error);
+ return null;
+ }
+}
+```
+
+This utility function:
+
+- Loads images from your Worker's assets
+- Automatically detects image content type
+- Converts images to base64 for use in OG images
+- Provides fallback handling if image loading fails
+
+Use it in your templates like this:
+
+```typescript
+const logoImage = await loadImage(c, "/images/your-logo.png");
+```
+
+:::note
+Make sure your images are stored in the `public/images` directory and referenced with paths starting with `/images/`.
+:::
+
+## 6. Implement the OG image generator
+
+Create the main image generation handler:
+
+```typescript title="src/og.tsx"
+import { Hono } from "hono";
+
+import { ImageResponse } from "@cloudflare/pages-plugin-vercel-og/api";
+
+const app = new Hono();
+
+export default app.get("/", async (c) => {
+ const { mainText, description, footerText } = c.req.query(); // Implementation details
+});
+```
+
+## 7. Add visual styles
+
+The OG image generator includes four distinct styles that can be selected via the `style` query parameter. The style selection is handled through a simple query parameter in the URL:
+
+```typescript
+style = 1; // Default professional style
+style = 2; // Eco-tech theme
+style = 3; // Corporate brand style
+style = 4; // GitHub profile style
+```
+
+If no style parameter is provided or an invalid value is used, the generator defaults to Style 1. Here's how to use each style:
+
+### Style 1: Professional (Default)
+
+
+
+```txt
+/og?style=1&mainText=Building%20the%20Future&description=Modern%20web%20development
+```
+
+Features:
+
+- Blue gradient background
+- Frosted glass card effect
+- Perfect for blog posts and articles
+
+### Style 2: Eco-Tech
+
+
+
+```txt
+/og?style=2&mainText=Green%20Summit&description=Sustainable%20Innovation
+```
+
+Features:
+
+- Green gradient theme
+- Semi-transparent overlay
+- Ideal for environmental or sustainability content
+
+### Style 3: Corporate
+
+
+
+```txt
+/og?style=3&mainText=Company%20Update&description=Q4%20Results
+```
+
+Features:
+
+- Warm gradient background
+- Logo integration
+- Professional corporate layout
+
+### Style 4: GitHub Profile
+
+
+
+```txt
+/og?style=4
+```
+
+Features:
+
+- Minimal design
+- GitHub avatar integration
+- Perfect for developer profiles
+
+:::tip
+You can combine any style with other parameters like `mainText`, `description`, and `footerText` to customize the output further.
+:::
+
+The style selection is implemented using a ternary chain in the code:
+
+```typescript title="src/index.ts"
+const SocialCardTemplate =
+ c.req.query("style") === "2"
+ ? Style2()
+ : c.req.query("style") === "3"
+ ? Style3()
+ : c.req.query("style") === "4"
+ ? Style4()
+ : Style1();
+```
+
+This implementation allows for easy addition of new styles in the future by simply adding new conditions to the chain and corresponding style components.
+
+```typescript title="src/og.tsx"
+function Style1() {
+ return (
+
+ {/* Style implementation */}
+
+ );
+}
+```
+
+## 8. Configure caching
+
+Enable caching to:
+
+- Reduce computation costs
+- Improve response times
+- Decrease origin server load
+- Provide consistent performance
+
+Here's how to implement caching with customizable durations:
+
+```typescript title="src/index.ts"
+import { Hono } from "hono";
+import { cache } from "hono/cache";
+
+const app = new Hono()
+ .use(
+ "*",
+ cache({
+ cacheName: async (c) => {
+ const url = new URL(c.req.url);
+ return `${c.req.method} ${url.pathname}${url.searchParams}`;
+ },
+ cacheControl: "max-age=86400",
+ }),
+ )
+ .route("og", og);
+```
+
+:::caution
+Make sure to configure appropriate cache durations based on your application's needs. The example uses a 24-hour cache duration.
+:::
+
+## Set up TypeScript type definitions
+
+Let's create our type definitions to ensure smooth TypeScript integration. Create a new file `src/type.d.ts`:
+
+```typescript title="src/type.d.ts"
+interface CacheStorage {
+ default: Cache;
+}
+
+declare module "@cloudflare/pages-plugin-vercel-og/api" {
+ import { ImageResponse as VercelImageResponse } from "@vercel/og";
+ export declare class ImageResponse extends Response {
+ constructor(...args: ConstructorParameters);
+ }
+}
+
+declare module "*.woff2" {
+ const content: ArrayBuffer;
+ export default content;
+}
+
+declare module "*.woff" {
+ const content: ArrayBuffer;
+ export default content;
+}
+
+declare module "*.ttf" {
+ const content: ArrayBuffer;
+ export default content;
+}
+```
+
+These type definitions are crucial for our project because they:
+
+- Enable TypeScript to understand Cloudflare's cache storage
+- Add proper typing for the Vercel OG image response
+- Allow direct importing of font files (`.woff2`, `.woff`, `.ttf`)
+
+With these definitions in place, you will get full TypeScript support and autocompletion throughout your project. This makes development smoother and helps catch potential issues early.
+
+## 9. Deploy your Worker
+
+Deploy the application to Cloudflare Workers:
+
+```bash
+bun run deploy
+```
+
+## Usage examples
+
+Generate OG images by making `GET` requests:
+
+```txt
+https://your-worker.workers.dev/og?mainText=Hello%20World&description=A%20dynamic%20OG%20image&style=1
+```
+
+You can customize the image by adjusting query parameters:
+
+- `mainText`: Main heading
+- `description`: Detailed description
+- `footerText`: Footer content
+- `style`: Visual style (1-4)
+
+## Conclusion
+
+Congratulations! You have successfully harnessed the power of Cloudflare Workers to build a dynamic OG image generator. By leveraging the global edge network and serverless architecture, your application now delivers high-performance visuals with ease. Whether you are scaling for millions of users or iterating on design tweaks, Cloudflare Workers ensure your images are always fast, reliable, and stunning.
+
+This solution provides:
+
+- Fast generation times through edge computing
+- Multiple font loading options
+- Pre-designed visual styles
+- Built-in caching support
+
+The complete source code is available on [GitHub](https://github.com/mohdlatif/og-image-generator-cloudflare-worker).
+
+## Related resources
+
+- [Cloudflare Workers documentation](/workers/)
+- [Hono framework](https://hono.dev/)
+- [Vercel OG Image Generation](https://vercel.com/docs/functions/og-image-generation)
+- [Cloudflare page plugin vercel/og](/pages/functions/plugins/vercel-og/)
+- [Tailwind CSS](https://tailwindcss.com/)