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

Tips for including extra items in a JSON String using Angular 2

function execute(req:any): any { var stReq = JSON.stringify(req); // Adding additional item "Cityname": "angular2City" inside req req.Cityname = 'angular2City'; } Now, how can I include the additional item "Cityname": "angular2C ...

Developing JSON with the use of jQuery

My latest project involves creating an application that converts HTML tables to JSON format. The code is functioning properly, but I've encountered an issue when the td or th elements contain inner components like span or other child elements. While I ...

The callback function fails to execute the click event following the .load() method

Hey there, I've hit a roadblock and could really use some help figuring out where I went wrong. Let me break down my script for you. On page1.html, I have a div that gets replaced by another div from page2.html using jQuery's .load() method. Here ...

Using $anchorScroll in Angular to create an anchor link that links to the same page but with a style change seems to be ineffective

I have a simple Angular view that includes a menu. Each item in the menu serves as a link to a specific section of the same page. I am utilizing $anchorScroll to achieve this functionality and it is functioning correctly. However, I am encountering an issu ...

I am attempting to secure a webpage with a password using JavaScript

I've been working on adding password protection to my webpage at , with the goal of allowing users to enter the password once per session. However, I've encountered an issue: if a user cancels out of the initial prompt or enters the wrong passwor ...

Is there a specific requirement for importing a React component into a particular file?

I am facing an issue with my component and two JavaScript files: index.js and App.js. When I import the component into index.js, it displays correctly on the screen. However, when I import it into App.js, nothing appears on the screen. Here is the code fr ...

Attempting to modify text using the header parameter has proven to be ineffective

pages/_middleware.ts import { NextRequest, NextResponse } from 'next/server'; const isMobile = (userAgent: string) => /iPhone|iPad|iPod|Android/i.test(userAgent); const propName = 'x-rewrite'; enum Device { desktop = 'no& ...

Is there a more "Angular-esque" approach to implementing this (inter-element communication)?

I have created a custom directive that will automatically add an asterisk to the label of any input field marked as required. The following is my link function with detailed comments: // This is what the DOM structure looks like: // <label id="label-1" ...

Adding "data-cy" attribute to Next.js Link with Cypress

Is there a way to add data-cy if the Link does not have an <a> element? <Link href="/about/"> <span data-cy="nav-item">About</span> </Link> Link to article on using Cypress with Next.js for end-to-end ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...

Guide to switching between 3 classes with mouseover using JavaScript

Currently, I am dealing with an unordered list that contains 4 items. The goal is to have the list grow to 100% of its width when hovered over, while all 'noun hovered li' items should shrink to a width of 0%. Once the cursor leaves, everything s ...

Struggling to comprehend the node.js walker concept

I am struggling to grasp the concept of how the signature/header of the node.js walker functions. I understand that a walker can go through a directory and apply filters, but I'm unsure about how the signature of the .on function works. For example: ...

Utilizing props in makeStyles for React styling

I have a component that looks like this: const MyComponent = (props) => { const classes = useStyles(props); return ( <div className={classes.divBackground} backgroundImageLink={props.product?.image} sx={{ position: "r ...

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

Unusual issue in IE causing rendering problems in reporting services

Currently, I am creating a report using Reporting Services 2008, MVC 2, and Ajax as my development technologies. When I generate the report, everything displays perfectly if there is data present. However, if there is no data, the report body gets cut off ...

Whenever I try to send an email in Node.js, I encounter 404 errors. Additionally,

I have an Angular application with a form that makes AJAX requests. Emailing works fine, but no matter what I set the response to, I get an error for the path '/send'. I assume Node.js expects the path '/send' to render a template or da ...

Issue with Trix text editor not triggering the change event

Lately, I've been facing some difficulties in getting the tirx-change event to trigger when there are changes in the content of a trix-editor. Despite using React JS for the view, I haven't been able to identify the problem. Below is the code sni ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

Error: The connect function is not recognized for the mongoose module

Currently, I'm facing an issue while attempting to establish a connection with my MongoDB database. The mongoose module has been imported in the following manner: import mongoose from "mongoose"; Upon trying to connect to the MongoDB databa ...