Browse Source

fix: load linked blog covers from their source, with fallbacks

Notion's image proxy is rate-limited by Wikimedia (429), so covers linked
from there came back 502 from the image optimizer and showed as empty
tiles on /blog, in link previews, and in structured data.

- Covers linked from other sites now load from where they live; covers
  uploaded to Notion still go through Notion.
- If the optimizer can't fetch a cover, the browser loads the original;
  if that fails too, an aurora wash with the post's initial stands in.
- Link previews in posts hide images their sites no longer serve.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QEPoSHwHCYMNpm2iKxY9hL
Claude 1 tháng trước cách đây
mục cha
commit
a293c34307

+ 3 - 3
app/blog/[blogId]/page.tsx

@@ -6,7 +6,7 @@ import {
   getAllBlogPosts,
   getPageContent,
   extractDescription,
-  customMapImageUrl,
+  coverImageUrl,
 } from "@/lib/notion";
 import { notionBlogConfig, siteConfig } from "@/config/site";
 
@@ -38,7 +38,7 @@ export async function generateMetadata({
   const block = blockOf(recordMap.block[blogId]);
   const coverUrl = block?.format?.page_cover;
   const ogImages = coverUrl
-    ? [{ url: customMapImageUrl(coverUrl, block), alt: postTitle }]
+    ? [{ url: coverImageUrl(coverUrl, block), alt: postTitle }]
     : [{ url: "/og-image.png", alt: postTitle }];
 
   return {
@@ -95,7 +95,7 @@ export default async function Page({
       dateModified: new Date(block.last_edited_time).toISOString(),
     }),
     ...(coverUrl && {
-      image: customMapImageUrl(coverUrl, block),
+      image: coverImageUrl(coverUrl, block),
     }),
     author: {
       "@type": "Person",

+ 2 - 2
app/blog/page.tsx

@@ -1,6 +1,6 @@
 import { Metadata } from "next";
 
-import { customMapImageUrl, getAllBlogPosts } from "@/lib/notion";
+import { coverImageUrl, getAllBlogPosts } from "@/lib/notion";
 import { notionBlogConfig } from "@/config/site";
 import { BlogList } from "@/components/blog/blog-list";
 
@@ -28,7 +28,7 @@ export default async function Page() {
   const postsWithImages = blogPosts.map((post) => ({
     ...post,
     imageUrl: post.pageCover
-      ? customMapImageUrl(post.pageCover, post.block)
+      ? coverImageUrl(post.pageCover, post.block)
       : undefined,
   }));
 

+ 2 - 12
components/blog/blog-list.tsx

@@ -1,6 +1,6 @@
-import Image from "next/image";
 import Link from "next/link";
 
+import { Cover } from "@/components/blog/cover";
 import { Eyebrow } from "@/components/cards/ui";
 import type { Blog } from "@/types/blog";
 
@@ -37,17 +37,7 @@ export function BlogList({ blogPosts }: { blogPosts: Post[] }) {
             href={`/blog/${id}`}
           >
             <div className="relative aspect-[16/9] overflow-hidden bg-card-2">
-              {imageUrl && (
-                <Image
-                  fill
-                  alt=""
-                  className="object-cover transition-transform duration-700 ease-out group-hover:scale-[1.04]"
-                  loading={i < 3 ? "eager" : "lazy"}
-                  preload={i === 0}
-                  sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 340px"
-                  src={imageUrl}
-                />
-              )}
+              <Cover index={i} src={imageUrl} title={title} />
             </div>
             <div className="flex flex-1 flex-col gap-2 p-5">
               <h2 className="text-[1.05rem] leading-snug font-semibold tracking-tight transition-colors group-hover:text-glacier">

+ 65 - 0
components/blog/cover.tsx

@@ -0,0 +1,65 @@
+"use client";
+
+import Image from "next/image";
+import { useState } from "react";
+
+// Hosts the image optimizer may fetch: images.remotePatterns in next.config.js.
+const OPTIMIZED = new Set([
+  "www.notion.so",
+  "upload.wikimedia.org",
+  "images.unsplash.com",
+]);
+
+const optimizable = (src: string) => {
+  try {
+    return OPTIMIZED.has(new URL(src).hostname);
+  } catch {
+    return false;
+  }
+};
+
+/**
+ * A post's cover. If the optimizer can't fetch it, the browser asks the
+ * source itself; if that fails too, a quiet aurora wash stands in.
+ */
+export function Cover({
+  src,
+  title,
+  index,
+}: {
+  src: string | undefined;
+  title: string;
+  index: number;
+}) {
+  // 0: optimized, 1: straight from the source, 2: gave up.
+  const [attempt, setAttempt] = useState(() =>
+    !src ? 2 : optimizable(src) ? 0 : 1,
+  );
+
+  if (!src || attempt > 1) {
+    return (
+      <div
+        aria-hidden
+        className="absolute inset-0 grid place-items-center bg-[radial-gradient(90%_120%_at_12%_0%,var(--aurora-a),transparent_62%),radial-gradient(80%_110%_at_100%_100%,var(--aurora-b),transparent_58%)]"
+      >
+        <span className="font-display text-[64px] leading-none text-ink/15 italic">
+          {title.trim().charAt(0)}
+        </span>
+      </div>
+    );
+  }
+
+  return (
+    <Image
+      fill
+      alt=""
+      className="object-cover transition-transform duration-700 ease-out group-hover:scale-[1.04]"
+      loading={index < 3 ? "eager" : "lazy"}
+      preload={index === 0}
+      sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 340px"
+      src={src}
+      unoptimized={attempt === 1}
+      onError={() => setAttempt((a) => a + 1)}
+    />
+  );
+}

+ 30 - 2
components/blog/notion-page.tsx

@@ -4,7 +4,7 @@ import dynamic from "next/dynamic";
 import Link from "next/link";
 import { useTheme } from "next-themes";
 import type { ExtendedRecordMap } from "notion-types";
-import { useMemo, useSyncExternalStore } from "react";
+import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
 import { NotionRenderer } from "react-notion-x";
 import { getBlockValue } from "notion-utils";
 
@@ -99,6 +99,34 @@ export const NotionPage = ({
     () => ({ Code, Collection, Equation, Pdf, Modal }),
     [],
   );
+  const articleRef = useRef<HTMLElement>(null);
+
+  // Link previews show images from other sites, which come and go: drop the dead ones.
+  useEffect(() => {
+    const root = articleRef.current;
+
+    if (!root) return;
+    const onError = (e: Event) => {
+      if (!(e.target instanceof HTMLImageElement)) return;
+      const box = e.target.closest<HTMLElement>(
+        ".notion-bookmark-link-icon, .notion-bookmark-image",
+      );
+
+      if (box) box.style.display = "none";
+    };
+
+    root.addEventListener("error", onError, true);
+    // An image that failed before hydration is loaded again so its error is heard.
+    root
+      .querySelectorAll<HTMLImageElement>(".notion-bookmark img")
+      .forEach((img) => {
+        if (img.complete && img.naturalWidth === 0) {
+          img.setAttribute("src", img.getAttribute("src") ?? "");
+        }
+      });
+
+    return () => root.removeEventListener("error", onError, true);
+  }, [recordMap]);
 
   if (!recordMap) {
     return null;
@@ -107,7 +135,7 @@ export const NotionPage = ({
   const created = getBlockValue(recordMap.block[rootPageId])?.created_time;
 
   return (
-    <article className="mx-auto max-w-[760px]">
+    <article ref={articleRef} className="mx-auto max-w-[760px]">
       <Link
         className="lg inline-flex h-9 items-center gap-1.5 rounded-full px-3.5 text-[13px] font-medium"
         data-cursor="All posts"

+ 20 - 0
lib/notion.ts

@@ -138,3 +138,23 @@ export const customMapImageUrl = (url: string, block: Block): string => {
 
   return url;
 };
+
+const NOTION_HOST =
+  /(^|\.)(notion\.so|notion\.com|notion-static\.com|notionusercontent\.com|amazonaws\.com)$/;
+
+/**
+ * A page cover's URL. Covers linked from other sites (Wikimedia, Unsplash, ...)
+ * load from where they live: Notion's image proxy gets rate-limited by some of
+ * them. Covers uploaded to Notion still go through Notion.
+ */
+export const coverImageUrl = (url: string, block: Block): string => {
+  try {
+    const { protocol, hostname } = new URL(url);
+
+    if (protocol === "https:" && !NOTION_HOST.test(hostname)) return url;
+  } catch {
+    // A Notion path such as /images/page-cover/..., handled below.
+  }
+
+  return customMapImageUrl(url, block);
+};

+ 9 - 0
next.config.js

@@ -17,6 +17,15 @@ const nextConfig = {
         protocol: "https",
         hostname: "www.notion.so",
       },
+      // Blog covers linked straight from their source (see coverImageUrl).
+      {
+        protocol: "https",
+        hostname: "upload.wikimedia.org",
+      },
+      {
+        protocol: "https",
+        hostname: "images.unsplash.com",
+      },
     ],
   },
   async headers() {