79265484

Date: 2024-12-09 15:15:41
Score: 1
Natty:
Report link

so I just made the metadata parameters to accept data from the params in the layout.jsx file. I made sure that the parameters are gotten from the page.mdx file itself like below & it works... Cant believe I was stuck here for so long. just leaving the code here so that it helps anyone like me because I havent seen a reply in stackOverflow that helped me

(inside mdx.js)

export async function getArticleBySlug(slug, type) {
  const filePath = path.join(process.cwd(), `src/app/${type}/${slug}/page.mdx`);

  if (!fs.existsSync(filePath)) {
    return null; // Return null if the file does not exist
  }

  const fileContent = fs.readFileSync(filePath, 'utf8');
  const { data, content } = matter(fileContent);

  return {
    metadata: data, // Frontmatter metadata
    content: await serialize(content), // Serialized MDX content
  };
}

(inside layout.jsx)

export async function generateMetadata({ params }) {
  // Dynamically load content based on the route
  const { slug } = params;
  let pageMetadata = {
    title: 'page title',
    description: 'page description',
    url: 'https://page/',
    image: 'https://page/defaultimage.png',
  };

  if (slug) {
    // Example for blog articles
    const articles = await loadArticles();
    const article = articles.find((a) => a.slug === slug);

    if (article) {
      pageMetadata = {
        title: `${article.title} - page`,
        description: article.description || pageMetadata.description,
        url: `https://page/${slug}`,
        image: article.image || pageMetadata.image,
      };
    }
  }

  return {
    title: {
      template: '%s - page',
      default: 'page description',
    },
    openGraph: {
      title: pageMetadata.title,
      description: pageMetadata.description,
      url: pageMetadata.url,
      type: 'website',
      images: [
        {
          url: pageMetadata.image,
          width: 800,
          height: 600,
          alt: 'image',
        },
      ],
    },
  };
}
Reasons:
  • Blacklisted phrase (1): stackOverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: wwon