next.js – next js dynamic page routing working in localhost but giving 500 error in production

This is part of my next js project. This website is running perfectly on localhost but when i deploy it on vercel, the /blogs/book/chapter page is giving me 500 error. I am not sure what exactly the problem is, I have tried various things but nothing is working for me. Help Please!

Dynamic Routing Folder Structure

Page Structure

blog.js

import Head from "next/head";
import Link from "next/link";
import Image from "next/image";
import fs from "fs";
import path from "path";
import styles from "../../styles/blog/Blog.module.css";
import { capitalise } from "../../components/blog/Capitalise";
import BlogData from "../../components/blog/BlogData";

export default function Blog({ bookNames }) {
    const getBookImg = (slug) => {
        let bookCover =
            "https://ik.imagekit.io/manav11goyal11/blog/cover/tr:w-600/blog.jpg";

        BlogData.forEach((val) => {
            if (val.slug == slug) {
                bookCover = val.coverImage;
            }
        });

        return bookCover;
    };

    return (
        <section className={styles.blog}>
            <Head>
                <title>Blog | Manav Goyal</title>
                <meta
                    name="description"
                    content="Read my blogs on various topics covering Development, Coding, Technology."
                />
            </Head>

            <h1>Blogs</h1>

            <div className={styles.blogItems}>
                {bookNames.map((val, idx) => (
                    <div className={styles.blogItem} key={idx}>
                        <Link href={`/blog/${val.slug}`}>
                            <a
                                // target="_blank"
                                rel="noreferrer"
                                className={styles.blogItemInfo}
                            >
                                <Image
                                    src={getBookImg(val.slug)}
                                    alt="Blog Cover"
                                    height={300}
                                    width={500}
                                />
                                <h2>{capitalise(val.slug)}</h2>
                            </a>
                        </Link>
                    </div>
                ))}
            </div>
        </section>
    );
}

export async function getStaticProps() {
    const bookFolders = fs.readdirSync(path.join("posts"));

    const bookNames = bookFolders.map((bookName) => {
        return {
            slug: bookName,
        };
    });

    return {
        props: {
            bookNames,
        },
    };
}

chapter.js

import fs from "fs";
import path from "path";
import Head from "next/head";
import { useRouter } from "next/router";
import matter from "gray-matter";
import { marked } from "marked";
import styles from "../../../styles/blog/Chapter.module.css";
import { capitalise } from "../../../components/blog/Capitalise";
import BlogPostBottom from "../../../components/blog/BlogPostBottom";

export default function Chapter({ book, chapter, frontmatter, content }) {
    // Router Variable
    const router = useRouter();

    // If fallback then show this
    if (router.isFallback) {
        return <div>Loading...</div>;
    }

    // Destructuring
    const { description } = frontmatter;

    return (
        <div className={styles.bookChapter}>
            <Head>
                <title>{`${capitalise(chapter)} | ${capitalise(
                    book
                )} | Blog | Manav Goyal`}</title>
                <meta
                    name="description"
                    content={`Read Blog about this book ${book} covering chapter ${chapter} of topics ${description}`}
                />
            </Head>

            <h1>{`${capitalise(chapter)} - ${capitalise(book)}`}</h1>

            <section
                className={styles.bookChapterContent}
                dangerouslySetInnerHTML={{ __html: marked(content) }}
            ></section>

            <BlogPostBottom slug={`/blog/${book}`} />
        </div>
    );
}

export async function getStaticPaths() {
    return {
        paths: [{ params: { book: "", chapter: "" } }],
        fallback: true,
    };
}

// Web crawlers, won't be served a fallback and instead the path will behave as in fallback: 'blocking'
// fallback: true is not supported when using `next export`
export async function getStaticProps({ params }) {
    const { book, chapter } = params;

    let chapterPost = await fs.promises.readFile(
        path.join(`posts/${book}/${chapter}.md`),
        "utf-8"
    );

    const { data: frontmatter, content } = matter(chapterPost);

    return {
        props: {
            book,
            chapter,
            frontmatter,
            content,
        },
        // revalidate: 1,
    };
}

book.js

import React from "react";
import Head from "next/head";
import Link from "next/link";
import fs from "fs";
import path from "path";
import matter from "gray-matter";
import styles from "../../../styles/blog/Book.module.css";
import { capitalise } from "../../../components/blog/Capitalise";

export default function Book({ book, chapters }) {
    return (
        <div className={styles.blogBook}>
            <Head>
                <title>{`${capitalise(book)} | Blog | Manav Goyal`}</title>
                <meta
                    name="description"
                    content={`Read Blog about this book ${book} covering chapter`}
                />
            </Head>

            <h1>Topics</h1>

            <div className={styles.blogBookChapters}>
                {chapters.map((post, idx) => (
                    <div className={styles.blogBookChaptersItem} key={idx}>
                        <Link href={`/blog/${book}/${post.slug}`}>
                            <a rel="noreferrer">
                                {/* <a target="_blank" rel="noreferrer"> */}
                                <h2>{capitalise(post.slug)}</h2>
                                <div>{post.frontmatter.description}</div>
                            </a>
                        </Link>
                    </div>
                ))}
            </div>
        </div>
    );
}

export async function getStaticPaths() {
    const bookFolders = fs.readdirSync(path.join("posts"));

    const bookNames = bookFolders.map((bookName) => {
        return { params: { book: bookName } };
    });

    return {
        paths: bookNames,
        fallback: false,
    };
}

export async function getStaticProps({ params }) {
    const { book } = params;
    const chapterFiles = fs.readdirSync(path.join(`posts/${book}`));

    const chapters = chapterFiles.map((chapterName) => {
        const slug = chapterName.replace(".md", "");

        const markdownWithMeta = fs.readFileSync(
            path.join(`posts/${book}`, chapterName),
            "utf-8"
        );

        const { data: frontmatter } = matter(markdownWithMeta);

        return {
            slug,
            frontmatter,
        };
    });

    console.log(book);

    return {
        props: {
            book,
            chapters: chapters.sort((a, b) => {
                return Date.parse(b.frontmatter.date) - Date.parse(a.frontmatter.date);
            }),
        },
    };
}

Posts Folder Structure

Posts Folder Structure

Vercel Build Error

Vercel Error

Next Config File

module.exports = {
    reactStrictMode: true,
    images: {
        domains: ["ik.imagekit.io"],
    },
};

Leave a Comment