Next.js Discord

Discord Forum

Firestore onSnapshot

Unanswered
Houss posted this in #help-forum
Open in Discord
I have a nextjs 14 app with a file lib/firebase.ts

import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
import { config } from "./config";

const firebaseConfig = {
    apiKey: config.FIREBASE_API_KEY,
    authDomain: config.FIREBASE_AUTH_DOMAIN,
    projectId: config.FIREBASE_PROJECT_ID,
    storageBucket: config.FIREBASE_STORAGE_BUCKET,
    messagingSenderId: config.FIREBASE_MESSAGING_SENDER_ID,
    appId: config.FIREBASE_APP_ID
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app)
export const firestore = getFirestore(app)


and lib/config.ts

import { object, string } from "zod"

const configSchema = object({
    API_TOKEN: string({ required_error: "API_TOKEN is required" })
        .min(1, "API_TOKEN is required"),

    SESSION_SECRET: string({ required_error: "SESSION_SECRET is required" })
        .min(1, "SESSION_SECRET is required"),

    NEXT_PUBLIC_FIREBASE_API_KEY: string({ required_error: "FIREBASE_API_KEY is required" })
        .min(1, "FIREBASE_API_KEY is required"),
    NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN: string({ required_error: "FIREBASE_AUTH_DOMAIN is required" })
        .min(1, "FIREBASE_AUTH_DOMAIN is required"),
    NEXT_PUBLIC_FIREBASE_PROJECT_ID: string({ required_error: "FIREBASE_PROJECT_ID is required" })
        .min(1, "FIREBASE_PROJECT_ID is required"),
    NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET: string({ required_error: "FIREBASE_STORAGE_BUCKET is required" })
        .min(1, "FIREBASE_STORAGE_BUCKET is required"),
    NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID: string({ required_error: "FIREBASE_MESSAGING_SENDER_ID is required" })
        .min(1, "FIREBASE_MESSAGING_SENDER_ID is required"),
    NEXT_PUBLIC_FIREBASE_APP_ID: string({ required_error: "FIREBASE_APP_ID is required" })
        .min(1, "FIREBASE_APP_ID is required")
})

export const config = configSchema.parse(process.env)

3 Replies

and on a "use client" page i'm trying to do onSnapshot to have real time data about a collection but it's giving me a zod error saying that the env variables are missing

i guess it's come from the fact that it's trying to use firebase.ts that uses the .env, from a client component which doesnt have access to the .env

So how can i fix this and get real time data with firebase in nextjs?
after some trying i found that in the firebase.ts if i don't use config. but directly process.env. it works fine
however i still want to keep the zod verification of the .env file, is there a way to make zod parse the env client side?