Creating a Document
In this tutorial we show how you can create a document in Firestore using the Web and Admin SDKs.
Creating a document in Firestore can be achieved using both the Web (Client) and the Admin SDK (Server). Depending on the use-case, you will use one or the other.
- Client SDK: When you want to create a document from the browser, you will use the Client SDK. This is the most common use-case, and can be done when the user has the permissions required to create a document based on their security rules.
- Admin SDK: When you want to create a document from a server, you will use the Admin SDK. This is useful when you want to create a document from a server, or when you want to create a document that the user does not have permission to create.
Client SDK
To create a document, we will use the addDoc
function from the Web Firebase SDK.
We can use hooks to make sure we have access to the Firestore instance, and the collection we want to add the document to.
import { useFirestore } from 'reactfire';import { useCallback } from 'react';import { addDoc, collection } from 'firebase/firestore';function useCreateTask() { const firestore = useFirestore(); const tasksCollection = collection(firestore, `/tasks`); return useCallback( (task: { title: string; description: string; completed: boolean; }) => { return addDoc(tasksCollection, task); }, [tasksCollection] );}
We can then use this hook in our component to create a new task.
import { useCallback } from "react";const CreateTaskForm = () => { const createTask = useCreateTask(); // ... other code const onSubmit = useCallback(async (task: { title: string; description: string; completed: boolean; }) => { await createTask(task); }, [createTask]); // ... other code};
Admin SDK
To create a document, we will use the add
function from the Admin Firebase SDK.
We can use the Admin SDK only in API Route handlers and the getServerSideProps
function. For two reasons:
- The Admin SDK is for Node.js environments, and cannot be used in the browser.
- The Admin SDK requires a service account, which should not be exposed to the browser.
import getRestFirestore from '~/core/firebase/admin/get-rest-firestore';async function addTaskFromServer(task: { title: string; description: string; completed: boolean;}) { const firestore = getRestFirestore(); const tasksCollection = firestore.collection(firestore, `tasks`); await tasksCollection.add(task); return task;}
You can now use the function addTaskFromServer
in your API Route handlers and getServerSideProps
functions.