Currently, I am in the process of developing a blog website, and most of it is completed except for the functionality of being able to click on a post stub to read the full post. Whenever I try to navigate to the post page, I encounter the following error:
Error: Error serializing
.post
returned fromgetServerSideProps
in "/posts/[slug]". Reason:undefined
cannot be serialized as JSON. Please usenull
or omit this value.
Despite my efforts to search for a solution, I have been unable to identify the root cause of this issue.
Below is a portion of my Firebase code:
import {
collection,
getDocs,
getFirestore,
limit,
onSnapshot,
orderBy,
query,
doc,
setDoc,
getDoc,
} from "firebase/firestore";
import firebase from "firebase/app";
import { initializeApp, getApps, getApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";
import { Timestamp, toJSON } from "firebase/firestore";
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyAB4SbXl-I1TMoa31ybnCzmTASXjZFnMAg",
authDomain: "personal-blog-8decb.firebaseapp.com",
projectId: "personal-blog-8decb",
storageBucket: "personal-blog-8decb.appspot.com",
messagingSenderId: "473768411808",
appId: "1:473768411808:web:c464d23c531b8bdaa4bfc5",
measurementId: "G-6F04591W4N",
};
if (!getApps().length) {
initializeApp(firebaseConfig);
}
const db = getFirestore();
//Reads all the posts in the database
export const getPosts = async () => {
const q = query(collection(db, "posts"), orderBy("date", "desc"));
const querySnapShot = await getDocs(q);
const posts = querySnapShot.docs.map((doc) => ({
...doc.data(),
id: doc.id,
date: doc.data().date?.toDate().getTime(),
}));
return posts;
};
// Get one post from the database based on the slug.
export const getPostBySlug = async (slug) => {
const docRef = doc(db, "posts", `${slug}`);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
return docSnap.data();
} else {
console.log("No Such Document");
}
};
// Adds posts to the database
export const createPost = async (post) => {
await setDoc(doc(db, "posts", `${post.slug}`), {
title: post.title,
content: post.content,
date: Timestamp.fromDate(new Date()),
});
};
export const auth = getAuth();
export const googleAuthProvider = new GoogleAuthProvider();
Furthermore, here is the code for the slug page:
import { async } from "@firebase/util";
import { useRouter } from "next/router";
import { getPostBySlug } from "../../lib/firebase";
import moment from "moment";
export async function getServerSideProps() {
const post = await getPostBySlug();
return {
props: {
post,
},
};
}
export default function PostPage({ post }) {
<div className="post">
<h1>{post.title}</h1>
<span>Published {moment(post.date).format("LL")}</span>
<p dangerouslySetInnerHTML={{ __html: post.content }}></p>
</div>;
}
Thank you in advance for any assistance provided.