Skip to content

Fix OGImage icon fetch on cloudflare #3253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 21, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 2 additions & 20 deletions packages/gitbook/src/routes/ogimage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { getAssetURL } from '@/lib/assets';
import { filterOutNullable } from '@/lib/typescript';
import { getCacheTag } from '@gitbook/cache-tags';
import type { GitBookSiteContext } from '@v2/lib/context';
import { getCloudflareContext } from '@v2/lib/data/cloudflare';
import { getResizedImageURL } from '@v2/lib/images';

const googleFontsMap: { [fontName in CustomizationDefaultFont]: string } = {
Expand Down Expand Up @@ -322,24 +321,6 @@ function logOnCloudflareOnly(message: string) {
}
}

/**
* Fetch a resource from the function itself.
* To avoid error with worker to worker requests in the same zone, we use the `WORKER_SELF_REFERENCE` binding.
*/
async function fetchSelf(url: string) {
const cloudflare = getCloudflareContext();
if (cloudflare?.env.WORKER_SELF_REFERENCE) {
logOnCloudflareOnly(`Fetching self: ${url}`);
return await cloudflare.env.WORKER_SELF_REFERENCE.fetch(
// `getAssetURL` can return a relative URL, so we need to make it absolute
// the URL doesn't matter, as we're using the worker-self-reference binding
new URL(url, 'https://worker-self-reference/')
);
}

return await fetch(url);
}

/**
* Read an image from a response as a base64 encoded string.
*/
Expand All @@ -363,6 +344,7 @@ const staticImagesCache = new Map<string, string>();
* Read a static image and cache it in memory.
*/
async function readStaticImage(url: string) {
logOnCloudflareOnly(`Reading static image: ${url}, cache size: ${staticImagesCache.size}`);
const cached = staticImagesCache.get(url);
if (cached) {
return cached;
Expand All @@ -377,7 +359,7 @@ async function readStaticImage(url: string) {
* Read an image from GitBook itself.
*/
async function readSelfImage(url: string) {
const response = await fetchSelf(url);
const response = await fetch(url);
const image = await readImage(response);
return image;
}