Recently I was working on a Nextjs project where I was using @google-cloud/firestore package to write and read data from firestore.
I had createdAt and updatedAt timestamps inside documents which I wanted to convert to data object on the frontend.
Since timestapms created using server side firestore package (@google-cloud/firestore or firebase-admin/firestore) timestamps containes "_" prefix with seconds and nanoseconds keys
{ _seconds: 1700832176, _nanoseconds: 968000000 }
and if we try to convert this timestamp to date on frontend it gives error.
TypeError: user.updatedAt.toDate is not a function
To fix this error you have to convert this timestamp to date object on the server. for example in Nextjs api route.
import { NextResponse } from "next/server";
import { db } from "./database";
export async function GET(req: Request) {
try {
const collectionRef = db
.collection("users")
const snapshot = await collectionRef.get();
const users = snapshot.docs.map((doc) => {
const data = doc.data();
return {
id: doc.id,
...data,
updatedAt: data.updatedAt.toDate(),
appointmentAt: data.appointmentAt.toDate(),
};
});
return NextResponse.json(appointments);
} catch (error) {
return NextResponse.json(error, {status: // status you want send })
}
}
Top comments (0)