Discover the ultimate guide to maintaining individual premium memberships in a Next.js application using the powerful combination of Redux, Firebase, and Stripe. Never worry about users losing their premium status again after

I have integrated Stripe for users to purchase premium subscriptions, but I am facing an issue with storing their premium status in Redux Persist State. After they log out, the state refreshes and upon logging back in, they are required to purchase a premium subscription again.

While I attempted to resolve this by using Redux Persist to save it in local storage, the problem persists as the premium status gets reset once the user logs out.

import { useEffect, useState } from "react";
import { getAuth, onIdTokenChanged } from "firebase/auth";
import { auth } from "../firebase";
import { useDispatch, useSelector } from "react-redux";
import { setPremiumStatus } from "@/redux/userSlice";

export default function usePremiumStatus(user) {
  const dispatch = useDispatch();
  const premiumStatus = useSelector((state) => state.user.premium);

  useEffect(
    () => {
      return onIdTokenChanged(auth, async (user) => {
        if (user) {
          const tokenResult = await user.getIdTokenResult();
          dispatch(
            setPremiumStatus(tokenResult.claims.stripeRole === "premium")
          );
        } else {
          dispatch(setPremiumStatus(false));
        }
      });
    },
    [user],
    dispatch
  );

  return premiumStatus;
}

The code snippet above demonstrates how I handle setting the premium status. Initially, it is set to "false", however, the dispatch function changes it to true. I am looking for a way to link the premium status to the user specifically. How can I achieve this?

Answer №1

Implementing such a system opens up the possibility for customers to easily manipulate their localStorage, giving them unauthorized access to premium features.

A more secure approach is to make a request to Stripe each time to search for a Customer using the provided email address and verify if they have an active Subscription.

Without knowledge of your specific integration with Stripe, it's challenging to provide detailed guidance, but I recommend applying the high-level logic outlined above to address this issue effectively.

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

Setting up an object with a set expiration using NodeJS and Mongoose

Is there a way to create a temporary entity (like an ad) that will automatically expire after one month using NodeJS with MongoDB? An ideal comparison would be Instagram or Facebook Stories that only last for 24 hours. ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

The build process encountered errors with webpack, causing npm run build to fail

My application encounters issues during the build process when executing npm run build or attempting to deploy on Vercel. However, running npm run dev works without any problems after I commented out the entire processingQueue.js file. Even before commenti ...

What is the reason behind using AJAX to attempt sending a new URL request on

Having a strange issue with my product list. When trying to edit a product by clicking on it, I am redirected to the product form where an AJAX request is supposed to be sent to getFiltersGroup. However, on error, the AJAX request is somehow being sent to ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

I'm having trouble sending registration emails through my server. What could be causing this issue?

Currently, I am in the process of developing a registration system that automatically sends an email with the user's username and password once they have successfully registered. The registration process functions smoothly up until the point where the ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Instead of using onload, activate function upon click instead

Upon page load, I have a function that executes: function loadData(page){ showLoading(); $.ajax({ type: "GET", url: "load_data.php", data: "page="+page, success: function(msg) { ...

``When you click, the image vanishes into thin

Could you please explain why the image disappears once I close the lightbox? Access with password: chough ...

Test failed due to missing Jest mocked data acquisition

Having an issue with my component that is supposed to load data from an API, but the test cannot find the element containing the data as it is mocked for testing purposes. component: import { useDispatch, useSelector } from "react-redux"; import ...

Please submit the form to log in with your credentials

Here is the HTML code snippet for a form where users can enter their username and password to log in: <form Name ="form1" Method ="POST" ACTION = "userlogin.php" id="form1"> <div id="main_body" class="full-width"> <label>User ...

Creating .html pages for dynamic routes in a Next.js application

Having a Next.js app (version 13.4.5) with a dynamic route /blog/[slug], I am looking to export the app as a static website. The directory structure is as follows: /app /blog /[slug] page.jsx page.jsx layout.jsx globals.css ... The n ...

Database entry does not appear in Internet Explorer until the browser is completely shut down and reopened

Currently, I have a form with two dropdowns. Selecting an option from the first dropdown automatically populates the second dropdown. Everything works well except for a minor issue I observed recently. When I add a new item to the second dropdown, it gets ...

Guide on how to display the next/image on a public IP domain

Hello, I am facing an issue with getting the src URL image using next/image. I have already set it up in next.config.js but I am still encountering errors. Here is my code: index.js <Image src={'http://110.100.190.222:9790/images/'+item.artic ...

The CSS selector functions as expected when used in a web browser, however, it

While conducting test automation using Selenium, I typically rely on css selectors to find elements. However, I recently came across a peculiar issue. I observed that in certain cases, the css selector works perfectly when tested in the browser console. Fo ...

Using HTML and CSS to generate an alpha mask on top of an image

I am currently working on a website and I am looking to create an effect where an image is masked by an overlay. The goal is to achieve a "fade out" effect, without any actual animation, but rather make it appear as if the image is gradually fading into th ...

I am having difficulty aligning the vertical touch event owl carousel

Here is the link: "jsfiddle.net/nLJ79/". Can you try to find a solution to make the owl carousel vertical? ...

No instances are returned by Processing.instances

I am experiencing an issue with a webpage that is running 2 processing sketches. I came across a suggestion to call Processing.instances[0].exit() in response to a question on dynamically unloading a Processing JS sketch from canvas. However, when I attem ...

How can I remove the popover parents when clicking the confirm button using jQuery?

I am having trouble sending an AJAX request and removing the parent of a popover after the request is successful. I can't seem to access the parent of the popover in order to remove it, which is causing me some frustration. // Code for deleting w ...

Utilizing a server for seamless communication between a mobile device and a website

Exploring a simple setup idea here: Imagine having a mobile app with a page that contains 4 lines of content (utilizing phonegap for development). The plan is to have a web page where data for those 4 lines can be inputted. Once the information is submitt ...