Skip to content

Application Crash if blog doesn't exist #4

@byP4ndaDev

Description

@byP4ndaDev

Hey,
While I was testing out the portfolio, I noticed something.
If you go to https://portfolio-magicui.vercel.app/blog/hello-world the app will work as expected. But if you go to https://portfolio-magicui.vercel.app/blog/hello-world1 the app will show an Application error
Screenshot 2024-08-02 022241

This happens because of this line in src/app/blog/[slug]/page.tsx:

let post = await getPost(params.slug);

if (!post) {
    notFound();
}

To be more specific. The error will appear because of the return of getPost(), which is this code:

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,
  };
}

If there is no hello-world1.mdx in the content folder, the function will crash and invoke the server side error.

Solution / Fix

To fix this problem, I changed the function into this:

export async function getPost(slug: string) {
  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,
    };
  }
}

Now go to src/app/blog/[slug]/page.tsx and change this line

if (!post) {
    notFound();
}

To this

if (!post.slug) {
    notFound();
}

Your src/app/blog/[slug]/page.tsx should now look like this:

let post = await getPost(params.slug);

if (!post.slug) {
  notFound();
}

The generateMetaData should look like this

export async function generateMetadata({
  params,
}: {
  params: {
    slug: string;
  };
}): Promise<Metadata | undefined> {
  let post = await getPost(params.slug);

  if(post.source) {
    let {
      title,
      publishedAt: publishedTime,
      summary: description,
      image,
    } = post.metadata;
    let ogImage = image ? `${DATA.url}${image}` : `${DATA.url}/og?title=${title}`;
  
    return {
      title,
      description,
      openGraph: {
        title,
        description,
        type: "article",
        publishedTime,
        url: `${DATA.url}/blog/${post.slug}`,
        images: [
          {
            url: ogImage,
          },
        ],
      },
      twitter: {
        card: "summary_large_image",
        title,
        description,
        images: [ogImage],
      },
    };
  }
}

If you now go to a blog that doesn't exist, you will see the Error 404 - Page not Found Page and no error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions