verified firebase/firestore requests

I've been struggling with the process of sending authenticated firebase/firestore calls. I set up firestore in my web app using Next.js as shown below:

import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore';
import { GoogleAuthProvider, getAuth } from "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

const app = initializeApp(firebaseConfig);

// firestore
export const db = getFirestore(app);

//auth
export const provider = new GoogleAuthProvider();
export const auth = getAuth();

Here's a snippet from one of my APIs:

import { db } from "../../../utils/db/init";
import {
  collection,
  addDoc,
  serverTimestamp,
  setDoc,
  doc,
} from "firebase/firestore";

/** [POST] Add user to database.
 * req.body requires:
 * @param email
 * @returns user
 */
export default async function addUserHandler(req, res) {
  try {
    const data = {
      ...req.body,
      createdAt: serverTimestamp(),
      followers: [],
      following: [],
    };
    const { id } = await addDoc(collection(db, "users"), data);
    await setDoc(doc(db, "users", id), { seed: id }, { merge: true }); // add seed for sorting posts (same as id)

    res.status(200).json({ ...data, id }); 
  } catch (error) {
    console.error(error);
    res.status(500).json(error.message);
  }
}

In my firestore rules:

...
match /users/{userId}{
    allow read, write: if request.auth.uid != null;
}

Even though the user is logged in when this API is called, firebase keeps showing

Missing or insufficient permissions
. What am I overlooking? How can I properly include authentication in the request?

Answer №1

Utilizing the Firebase client SDK in the client-side of your application is crucial. This explains why you may encounter the error message stating

Missing or insufficient permissions
, as security rules are designed to apply on the client side, while the server should be a trusted environment.

If you need to work with the Firebase SDK on the server end, it's recommended to employ the Firebase Admin SDK.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure the browser stays anchored at the bottom of the page while employing jQuery to reveal a div

This piece of code allows me to toggle the visibility of a div: <a href="#" class="show_hide">Show/hide</a> <div class="slidingDiv"> My content...... <a href="#" class="show_hide">hide</a></div> <script src="http:// ...

The module 'SharedModule' has imported an unexpected value of 'undefined'

When working with an Angular application, I want to be able to use the same component multiple times. The component that needs to be reused is called DynamicFormBuilderComponent, which is part of the DynamicFormModule. Since the application follows a lib ...

Challenges with JSON Documents

const fs = require('fs'); const express = require('express'); const app = express(); app.use(express.json()); app.get('/submit', (req, res) => { let Com_Title = req.query.ComTitle; let Com_Text = req.query.ComTex ...

Utilizing the power of moment.js within an Angular component

My goal is to utilize the moment() function within double curly braces {{}} in order to present a date: {{ moment().date(timeslot.start.value.month) .month(timeslot.start.value.dayOfMonth - 1) .format("MMMM Do") }} Unfortunately, I ...

Issue with Vue.js: document.querySelector is returning a null value even though the element clearly exists

I'm currently working on implementing a responsive navbar following Kevin Powell's tutorial, but I've run into an issue. For some reason, when I try to select the element with the class 'primary-navigation' using 'const primar ...

Guide to displaying a partial in the controller following an ajax request

After initiating an AJAX request to a method in my controller, I am attempting to display a partial. Below is the AJAX call I am currently using: $('.savings_link').click(function(event){ $.ajax({ type: 'GET', url: '/topi ...

AWS is not picking up NextJS MDX files, despite them working fine on local servers

Assortment of Packages: "@next/mdx": "^14.0.4", "next": "13.5.6", docker setup FROM --platform=linux/amd64 node:20-bullseye WORKDIR /app COPY tsconfig.json . COPY package.json . COPY package-lock.json . CO ...

Adjust the height for just one md-tab

Looking to find a way to set the height of the content within an <md-tab> element to be 100% in a flexible manner. For example, consider the following structure: <body> <md-content> <md-tabs> <md-tab label= ...

Object contents shift upon my first gaze

While working on my JavaScript/ReactJS code, I encountered an issue where the Object (Obj) I was printing in the console contained keys as ids and values as true/false statuses, but when I opened the object, the values would automatically change. For exam ...

What are some effective design principles for creating REST APIs in expressjs?

To streamline my code organization, I made the decision to create a methods folder. Within this folder, I store individual JavaScript files for each URL endpoint (such as website.com/billings). //expressJS configuration... const billings = require('. ...

There seems to be a hiccup in the JavaScript Console. It could potentially impact the functionality

Hey there, I'm encountering a strange issue in my IE 11 console. A JavaScript Console error has occurred. This may impact functionality. Whenever I try to run a for loop to create a list of elements within a ul tag 4000 times, the process stops at ...

Can Jquery mobile detect drag gestures?

Is there an event in Jquery Mobile that allows you to hide/show a div by dragging it, similar to the effect seen on phones? I have searched on different platforms and found that using Jquery UI is the closest solution. Is it possible to achieve this only ...

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

Does anyone have any insights into the technology that powers Twiddla's browsing features?

After some observation, I came to understand that simply inserting <iframe src=remote-page-here></iframe> will not work as expected. Interestingly, the website twiddla does not use flash either. I am intrigued by how they achieve the in-place b ...

Understanding the Access-Control-Allow-Headers in preflight response for Wordpress and VueJS

Attempting to retrieve a route from candriam-app.nanosite.tech to candriam.nanosite.tech has proven challenging. Despite various attempts to allow headers, I continue to encounter this CORS error: Access to fetch at 'https://xxxA/wp-json/nf-submission ...

Click to copy: Utilizing Italics in React Components

I've successfully implemented a way to copy text to the clipboard using React. Now, I'm facing the challenge of making only the content of this.state.parties italicized, while keeping the content of this.state.citation non-italicized when pasting ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Issue encountered while trying to obtain user authorization_code from Microsoft Graph

I am encountering an issue with obtaining the Authorization code for the user. After the user logs in, I extract the user code from the URL and then use Ajax to fetch the access_token. However, during this process, I encounter the following error : AADS ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

Perform validation on input by monitoring checkbox changes in Angular 4

I am currently working on a project where I need to loop through an array of key values in order to create a list of checkboxes, each accompanied by a disabled input field as a sibling. The requirement is that upon checking a checkbox, the corresponding in ...