From b3a6d4e0bbdb4ffb49050c3e239d11a8a61d90ec Mon Sep 17 00:00:00 2001 From: g-but Date: Wed, 5 Mar 2025 09:43:05 +0100 Subject: [PATCH] Fix server-side error and inline image loading issues --- app/blog/[slug]/page.tsx | 92 +++++++++++++--------- components/blog/MDXComponents.tsx | 125 ++++++++++++++++++------------ lib/blog.ts | 66 ++++++++++++++-- 3 files changed, 190 insertions(+), 93 deletions(-) diff --git a/app/blog/[slug]/page.tsx b/app/blog/[slug]/page.tsx index 7afd4ca..dfe0405 100644 --- a/app/blog/[slug]/page.tsx +++ b/app/blog/[slug]/page.tsx @@ -12,53 +12,70 @@ import remarkGfm from 'remark-gfm'; // Generate static paths for all blog posts export async function generateStaticParams() { - const posts = await fetchBlogPosts(); - return posts.map((post) => ({ - slug: post.slug, - })); + try { + const posts = await fetchBlogPosts(); + return posts.map((post) => ({ + slug: post.slug, + })); + } catch (error) { + console.error("Error generating static params:", error); + return []; + } } // Generate metadata for the page export async function generateMetadata({ params }: { params: { slug: string } }): Promise { - const post = await fetchBlogPostBySlug(params.slug); - - if (!post) { + try { + const post = await fetchBlogPostBySlug(params.slug); + + if (!post) { + return { + title: 'Post Not Found | Botsmann', + }; + } + return { - title: 'Post Not Found | Botsmann', + title: `${post.title} | Botsmann Blog`, + description: post.excerpt, + openGraph: { + title: post.title, + description: post.excerpt, + type: 'article', + publishedTime: post.date, + authors: [post.author], + images: post.featuredImage ? [ + { + url: post.featuredImage, + width: 1200, + height: 630, + alt: post.title + } + ] : [], + }, + twitter: { + card: 'summary_large_image', + title: post.title, + description: post.excerpt, + images: post.featuredImage ? [post.featuredImage] : [], + } + }; + } catch (error) { + console.error("Error generating metadata:", error); + return { + title: 'Error | Botsmann', }; } - - return { - title: `${post.title} | Botsmann Blog`, - description: post.excerpt, - openGraph: { - title: post.title, - description: post.excerpt, - type: 'article', - publishedTime: post.date, - authors: [post.author], - images: post.featuredImage ? [ - { - url: post.featuredImage, - width: 1200, - height: 630, - alt: post.title - } - ] : [], - }, - twitter: { - card: 'summary_large_image', - title: post.title, - description: post.excerpt, - images: post.featuredImage ? [post.featuredImage] : [], - } - }; } export default async function BlogPost({ params }: { params: { slug: string } }) { console.log('Rendering blog post for slug:', params.slug); try { + if (!params.slug) { + console.error('Missing slug parameter'); + notFound(); + } + const post = await fetchBlogPostBySlug(params.slug); if (!post) { @@ -71,7 +88,12 @@ export default async function BlogPost({ params }: { params: { slug: string } }) ...MDXComponents, img: (props: any) => { console.log('Rendering img with slug:', params.slug); - return MDXComponents.img({ ...props, slug: params.slug }); + // Make a defensive copy of props to avoid mutation issues + return MDXComponents.img({ + ...props, + slug: params.slug, + key: `img-${props.src}-${params.slug}` // Add key for React rendering + }); }, }; diff --git a/components/blog/MDXComponents.tsx b/components/blog/MDXComponents.tsx index 23a9979..652695b 100644 --- a/components/blog/MDXComponents.tsx +++ b/components/blog/MDXComponents.tsx @@ -2,7 +2,7 @@ import Image from 'next/image'; import Link from 'next/link'; -import { DetailedHTMLProps, ImgHTMLAttributes } from 'react'; +import { DetailedHTMLProps, ImgHTMLAttributes, useState, useEffect } from 'react'; // Helper function to transform image paths const transformImageSrc = (src: string, slug: string) => { @@ -106,68 +106,91 @@ const MDXComponents = { // Media elements img: (props: DetailedHTMLProps, HTMLImageElement> & { slug?: string }) => { const { src, alt, slug } = props; + const [imageSrc, setImageSrc] = useState(''); + const [isError, setIsError] = useState(false); if (!src) { console.error('Image source missing'); return
Image source missing
; } - // Log the image source and slug for debugging - console.log('MDX img processing:', { src, slug }); - - // Get the slug from props - const contextSlug = typeof slug === 'string' ? slug : ''; - - try { - // Process the image source - let fullSrc = ''; + // Process the image source + useEffect(() => { + // Log the image source and slug for debugging + console.log('MDX img processing:', { src, slug }); - if (src.startsWith('http')) { - // If it's already an absolute URL, use it as is - fullSrc = src; - } else if (src.startsWith('./') || src.startsWith('../')) { - // If it's a relative path and we have a slug, convert to GitHub raw URL - if (!contextSlug) { - console.error('Missing slug for relative image path:', src); - return
Unable to resolve image: missing post context
; + // Get the slug from props + const contextSlug = typeof slug === 'string' ? slug : ''; + + try { + let fullSrc = ''; + + if (src.startsWith('http')) { + // If it's already an absolute URL, use it as is + fullSrc = src; + } else if (src.startsWith('./') || src.startsWith('../')) { + // If it's a relative path and we have a slug, convert to GitHub raw URL + if (!contextSlug) { + console.error('Missing slug for relative image path:', src); + setIsError(true); + return; + } + + const imagePath = src.replace(/^\.\//, ''); // Remove leading ./ + fullSrc = `https://raw.githubusercontent.com/g-but/botsmann-blog-content/main/posts/${contextSlug}/${imagePath}`; + } else { + // For any other format, just use the src as is + fullSrc = src; } - const imagePath = src.replace(/^\.\//, ''); // Remove leading ./ - fullSrc = `https://raw.githubusercontent.com/g-but/botsmann-blog-content/main/posts/${contextSlug}/${imagePath}`; - } else { - // For any other format, just use the src as is - fullSrc = src; + // Log the processed image source for debugging + console.log('Processed image source:', fullSrc); + setImageSrc(fullSrc); + } catch (error) { + console.error('Error processing image:', error); + setIsError(true); } - - // Log the processed image source for debugging - console.log('Processed image source:', fullSrc); - - return ( -
- {alt { - console.error('Image load error:', fullSrc); - - // Try to find an alternative format - const altSrc = await useAlternativeImageFormat(fullSrc); - if (altSrc) { - console.log('Using alternative image format:', altSrc); - (e.target as HTMLImageElement).src = altSrc; - } - }} - /> - {alt &&

{alt}

} -
- ); - } catch (error) { - console.error('Error processing image:', error); + }, [src, slug]); + + if (isError) { return
Failed to load image
; } + + if (!imageSrc) { + return
Loading image...
; + } + + // Check for alternative formats when the image fails to load + const handleImageError = () => { + console.error('Image load error:', imageSrc); + + // Try alternative format + if (imageSrc.endsWith('.jpg')) { + const jfifSrc = imageSrc.replace(/\.jpg$/, '.jfif'); + console.log('Trying alternative format:', jfifSrc); + setImageSrc(jfifSrc); + } else if (imageSrc.endsWith('.jfif')) { + const jpgSrc = imageSrc.replace(/\.jfif$/, '.jpg'); + console.log('Trying alternative format:', jpgSrc); + setImageSrc(jpgSrc); + } else { + setIsError(true); + } + }; + + return ( +
+ {alt + {alt &&

{alt}

} +
+ ); }, // Custom components diff --git a/lib/blog.ts b/lib/blog.ts index 675468c..b3ba73f 100644 --- a/lib/blog.ts +++ b/lib/blog.ts @@ -17,6 +17,23 @@ const GITHUB_USERNAME = 'g-but'; const GITHUB_REPO = 'botsmann-blog-content'; const GITHUB_BRANCH = 'main'; +// Base URL for raw GitHub content +const GITHUB_RAW_BASE = `https://raw.githubusercontent.com/${GITHUB_USERNAME}/${GITHUB_REPO}/${GITHUB_BRANCH}`; + +// Function to check if a file exists on GitHub +async function fileExistsOnGitHub(path: string): Promise { + try { + const response = await fetch(`${GITHUB_RAW_BASE}/${path}`, { + method: 'HEAD', + cache: 'no-store' + }); + return response.ok; + } catch (error) { + console.error(`Error checking if file exists: ${path}`, error); + return false; + } +} + // Function to fetch all blog posts export async function fetchBlogPosts(): Promise { try { @@ -45,7 +62,7 @@ export async function fetchBlogPosts(): Promise { // Fetch the index.mdx file for this post const mdxRes = await fetch( - `https://raw.githubusercontent.com/${GITHUB_USERNAME}/${GITHUB_REPO}/${GITHUB_BRANCH}/posts/${slug}/index.mdx`, + `${GITHUB_RAW_BASE}/posts/${slug}/index.mdx`, { cache: 'no-store' } ); @@ -71,14 +88,26 @@ export async function fetchBlogPosts(): Promise { if (data.featuredImage) { // Remove ./ prefix if present const imagePath = data.featuredImage.replace(/^\.\//, ''); - featuredImage = `https://raw.githubusercontent.com/${GITHUB_USERNAME}/${GITHUB_REPO}/${GITHUB_BRANCH}/posts/${slug}/${imagePath}`; + featuredImage = `${GITHUB_RAW_BASE}/posts/${slug}/${imagePath}`; // Verify the image exists try { - const imageRes = await fetch(featuredImage, { method: 'HEAD' }); - if (!imageRes.ok) { + const imageExists = await fileExistsOnGitHub(`posts/${slug}/${imagePath}`); + if (!imageExists) { console.warn(`Featured image not found for ${slug}: ${featuredImage}`); - featuredImage = undefined; + + // Try alternative image formats + const fileNameWithoutExt = imagePath.replace(/\.(jpg|jpeg|png|gif|webp|jfif)$/, ''); + + // Try common image extensions + for (const ext of ['jpg', 'jpeg', 'png', 'webp', 'jfif']) { + const altPath = `posts/${slug}/${fileNameWithoutExt}.${ext}`; + if (await fileExistsOnGitHub(altPath)) { + featuredImage = `${GITHUB_RAW_BASE}/${altPath}`; + console.log(`Found alternative featured image for ${slug}: ${featuredImage}`); + break; + } + } } } catch (error) { console.error(`Error checking featured image for ${slug}:`, error); @@ -114,9 +143,14 @@ export async function fetchBlogPostBySlug(slug: string): Promise