Having trouble with stripe as it keeps making a new subscription for the user after every refresh

import Stripe from 'stripe';
import { NextResponse, NextRequest } from "next/server";

const stripeSecretKey = process.env.STRIPE_SECRET_KEY as string; 

const stripe = new Stripe(stripeSecretKey, {
     apiVersion: '2024-06-20',
});


export async function POST(req: NextRequest) {

  try {
    const data = await req.json();
    const { priceId, userId, email } = data;

    if (!userId) {
      throw new Error("User ID is not provided");
    }

    const customer = await stripe.customers.create({
      metadata: {
        userId: userId,
      },
      email: email
    });


    const subscription = await stripe.subscriptions.create({
      customer: customer.id,
      items: [{ price: priceId }], 
      payment_behavior: 'default_incomplete',
      collection_method: 'charge_automatically', 
      expand: ['latest_invoice.payment_intent'],
      payment_settings:{
        payment_method_types: ['card']
      }
    });

    const latestInvoice = subscription.latest_invoice;
    if (!latestInvoice || typeof latestInvoice === 'string') {
      throw new Error('Latest invoice is not available or is of unexpected type');
    }

    const paymentIntent = latestInvoice.payment_intent;
    if (!paymentIntent || typeof paymentIntent === 'string') {
      throw new Error('Payment intent is not available or is of unexpected type');
    }

    return NextResponse.json({ clientSecret: paymentIntent.client_secret }, { status: 200 });

  } catch (error) {
    console.error('Error creating subscription:', error);
    return NextResponse.json({ error: error }, { status: 400 });
  }
}
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /customers/{uid} {
      allow read, write: if request.auth != null && request.auth.uid == uid;

      match /checkout_sessions/{id} {
        allow read, write: if request.auth != null && request.auth.uid == uid;
      }
      match /subscriptions/{id} {
        allow read: if request.auth != null && request.auth.uid == uid;
      }
      match /payments/{id} {
        allow read: if request.auth != null && request.auth.uid == uid;
      }
    }

    match /products/{id} {
      allow read: if true;

      match /prices/{id} {
        allow read: if true;
      }

      match /tax_rates/{id} {
        allow read: if true;
      }
    }
  }
}
   
    const userRef = doc(db, "customers", userId);
    const userDoc = await getDoc(userRef);

    if (userDoc.exists()) {
      const userData = userDoc.data();
      if (userData.subscriptionId) {
       
        const subscriptionId = userData.subscriptionId;
        const subscription = await stripe.subscriptions.retrieve(subscriptionId, {
          expand: ['latest_invoice.payment_intent'],
        });

        if (subscription.latest_invoice && typeof subscription.latest_invoice !== 'string') {
          const paymentIntent = subscription.latest_invoice.payment_intent;

          if (paymentIntent && typeof paymentIntent !== 'string') {
            return NextResponse.json({ clientSecret: paymentIntent.client_secret }, { status: 200 });
          }
        }

        throw new Error('Payment intent not found or invalid');
      }
    }


Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 147ms
Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 147ms
[2024-08-11T21:41:23.341Z]  @firebase/firestore: Firestore (10.12.3): GrpcConnection RPC 'Listen' stream 0x3b35bbba error. Code: 1 Message: 1 CANCELLED: Disconnecting idle stream. Timed out waiting for new targets.
 GET /signUp 200 in 38ms
Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 260ms
Error creating subscription: [FirebaseError: Missing or insufficient permissions.] {
  code: 'permission-denied',
  customData: undefined,
  toString: [Function (anonymous)]
}
 POST /api/subscribe 400 in 260ms
[2024-08-11T23:05:36.893Z]  @firebase/firestore: Firestore (10.12.3): GrpcConnection RPC 'Listen' stream 0x3b35bbbb error. Code: 1 Message: 1 CANCELLED: Disconnecting idle stream. Timed out waiting for new targets.

So Im trying to set up stripe payment for my project that I’m also using firebase to manage my auth. Im having trouble every time I load my /signUp page it will attempt to create two separate subscriptions, or if i refresh the page it will do the same thing i want it to create one subscription per user and then update that subscription. How would I do this.

I’ve adding the check above but getting a permission error

the first code is my subscribe api that is working but will create multiple subscription for a user including when refreshing the page

the second is my rules that i have in firestore

the third code was my attempt to include a check to see if a subscription attempt has been made on the user currently logged in

and the last bit is the error i was getting following

sorry this is my first time using stack so bare with me please