mirror of
https://github.com/bitbaum/botsmann.git
synced 2026-12-04 15:58:20 +01:00
Fix server-side error and inline image loading issues
This commit is contained in:
1 parent
28036bc9b8
commit
b3a6d4e0bb
3 files changed
+190
-93
No files matched your search
+57
-35
@@ -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<Metadata> {
|
||||
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
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -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<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> & { slug?: string }) => {
|
||||
const { src, alt, slug } = props;
|
||||
const [imageSrc, setImageSrc] = useState<string>('');
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
if (!src) {
|
||||
console.error('Image source missing');
|
||||
return <div className="my-8 p-4 bg-red-50 text-red-500">Image source missing</div>;
|
||||
}
|
||||
|
||||
// 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 <div className="my-8 p-4 bg-yellow-50 text-yellow-700">Unable to resolve image: missing post context</div>;
|
||||
// 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 (
|
||||
<div className="my-8">
|
||||
<Image
|
||||
src={fullSrc}
|
||||
alt={alt || ''}
|
||||
width={800}
|
||||
height={450}
|
||||
className="rounded-lg"
|
||||
onError={async (e) => {
|
||||
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 && <p className="mt-2 text-sm text-gray-500 italic">{alt}</p>}
|
||||
</div>
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Error processing image:', error);
|
||||
}, [src, slug]);
|
||||
|
||||
if (isError) {
|
||||
return <div className="my-8 p-4 bg-red-50 text-red-500">Failed to load image</div>;
|
||||
}
|
||||
|
||||
if (!imageSrc) {
|
||||
return <div className="my-8 p-4 bg-gray-50 text-gray-500">Loading image...</div>;
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div className="my-8">
|
||||
<Image
|
||||
src={imageSrc}
|
||||
alt={alt || ''}
|
||||
width={800}
|
||||
height={450}
|
||||
className="rounded-lg"
|
||||
onError={handleImageError}
|
||||
/>
|
||||
{alt && <p className="mt-2 text-sm text-gray-500 italic">{alt}</p>}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
|
||||
// Custom components
|
||||
|
||||
+59
-7
@@ -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<boolean> {
|
||||
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<BlogPost[]> {
|
||||
try {
|
||||
@@ -45,7 +62,7 @@ export async function fetchBlogPosts(): Promise<BlogPost[]> {
|
||||
|
||||
// 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<BlogPost[]> {
|
||||
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<BlogPost | null
|
||||
try {
|
||||
console.log('Fetching blog post for slug:', slug);
|
||||
|
||||
if (!slug) {
|
||||
console.error('Attempted to fetch blog post with empty slug');
|
||||
return null;
|
||||
}
|
||||
|
||||
// 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' } // Always fetch fresh content
|
||||
);
|
||||
|
||||
@@ -142,10 +176,28 @@ export async function fetchBlogPostBySlug(slug: string): Promise<BlogPost | null
|
||||
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}`;
|
||||
|
||||
// Log the resolved featured image URL
|
||||
console.log(`Resolved featured image for ${slug}:`, featuredImage);
|
||||
|
||||
// Verify the image exists
|
||||
const imageExists = await fileExistsOnGitHub(`posts/${slug}/${imagePath}`);
|
||||
if (!imageExists) {
|
||||
console.warn(`Featured image not found: ${featuredImage}`);
|
||||
|
||||
// Try alternative formats
|
||||
const fileNameWithoutExt = imagePath.replace(/\.(jpg|jpeg|png|gif|webp|jfif)$/, '');
|
||||
|
||||
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: ${featuredImage}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return the blog post data
|
||||
|
||||
Reference in new issue
Block a user