From fbbc63f143fece5d8b83d98d7d2f2621fa8b2a8b Mon Sep 17 00:00:00 2001 From: byPandaDev Date: Sun, 4 Aug 2024 09:33:33 +0200 Subject: [PATCH] Fixed Blog Page if not Found --- src/app/blog/[slug]/page.tsx | 58 +++++++++++++++++++----------------- src/data/blog.ts | 26 ++++++++++------ 2 files changed, 47 insertions(+), 37 deletions(-) diff --git a/src/app/blog/[slug]/page.tsx b/src/app/blog/[slug]/page.tsx index 87cd0f6..449de9c 100644 --- a/src/app/blog/[slug]/page.tsx +++ b/src/app/blog/[slug]/page.tsx @@ -14,36 +14,38 @@ export async function generateMetadata({ }): Promise { let post = await getPost(params.slug); - let { - title, - publishedAt: publishedTime, - summary: description, - image, - } = post.metadata; - let ogImage = image ? `${DATA.url}${image}` : `${DATA.url}/og?title=${title}`; - - return { - title, - description, - openGraph: { + if(post.source) { + let { title, - description, - type: "article", - publishedTime, - url: `${DATA.url}/blog/${post.slug}`, - images: [ - { - url: ogImage, - }, - ], - }, - twitter: { - card: "summary_large_image", + publishedAt: publishedTime, + summary: description, + image, + } = post.metadata; + let ogImage = image ? `${DATA.url}${image}` : `${DATA.url}/og?title=${title}`; + + return { title, description, - images: [ogImage], - }, - }; + openGraph: { + title, + description, + type: "article", + publishedTime, + url: `${DATA.url}/blog/${post.slug}`, + images: [ + { + url: ogImage, + }, + ], + }, + twitter: { + card: "summary_large_image", + title, + description, + images: [ogImage], + }, + }; + } } export default async function Blog({ @@ -55,7 +57,7 @@ export default async function Blog({ }) { let post = await getPost(params.slug); - if (!post) { + if (!post.slug) { notFound(); } diff --git a/src/data/blog.ts b/src/data/blog.ts index 23a6d46..039936e 100644 --- a/src/data/blog.ts +++ b/src/data/blog.ts @@ -37,15 +37,23 @@ export async function markdownToHTML(markdown: string) { } export async function getPost(slug: string) { - const filePath = path.join("content", `${slug}.mdx`); - let source = fs.readFileSync(filePath, "utf-8"); - const { content: rawContent, data: metadata } = matter(source); - const content = await markdownToHTML(rawContent); - return { - source: content, - metadata, - slug, - }; + try { + const filePath = path.join("content", `${slug}.mdx`); + let source = fs.readFileSync(filePath, "utf-8"); + const { content: rawContent, data: metadata } = matter(source); + const content = await markdownToHTML(rawContent); + return { + source: content, + metadata, + slug, + }; + } catch (error) { + return { + source: null, + metadata: null, + slug: null, + }; + } } async function getAllPosts(dir: string) {