Next.js and Firebase
Unanswered
Spectacled bear posted this in #help-forum
Spectacled bearOP
What is the best way of working with Next.js and firebase? How to send request from server components? Sry not sure if this is right place to ask the question?
4 Replies
I use [server actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations) to interact with data with a set up like:
// adding a document
"use server";
import { collection, addDoc } from "firebase/firestore";
import { db } from "@/lib/firebase";
export async function upload(data: Data) {
try {
const docRef = await addDoc(collection(db, "directory"), {
...data
})
} catch (e) {
console.error(e)
}
}
// lib/firebase.ts
import { getApps, initializeApp, getApp, FirebaseOptions } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig: FirebaseOptions = {
//... your env variables
};
export const app = getApps().length ? getApp() : initializeApp(firebaseConfig);
export const db = getFirestore(app);
server components (rsc) are basically every file without "use client" at the top
so u can call any function from firebase.ts directly in your page.tsx or whever u want