Is there a method to retrieve user information from the Stripe API using getServerSideProps in Next.JS?

I'm currently facing a challenge in retrieving user data from Stripe within the getServerSideProps function in Next.JS. My goal is to pass this data down to other components, but I'm struggling to extract it from the getServerSideProps function.

Here's my implementation of the getServerSideProps function:

export const getServerSideProps = withPageAuthRequired({

  async getServerSideProps(context) {
    const user = getSession(context.req, context.res).user

    const resources = await table.select({}).all()
    const customer = await fetch(`/api/customers`).then(res => res.json()).then(data => {
      data.data.find(user_data => user_data.metadata['auth0_user_id'] === user.sub);
    })

    const subscriber_status = await customer.metadata['subscription_status'] === 'true';


    return {
      props: {
        tech_resources: minifyRecords(resources),
        subscriber_stats: subscriber_status, // I aim to retrieve and return the subscriber status for future component usage
      }
    }
  }

});

Below is my initial fetch request that successfully retrieves the desired data either as a standalone function or when used with a useEffect hook.

fetch(`/api/customers`).then(res => res.json()).then(data => {
            const customer = data.data.find(user_data => user_data.metadata['auth0_user_id'] === user.sub);
            if (customer.metadata['subscription_status'] === 'true') {
                // Do Something;
            }
}

Unfortunately, attempting to incorporate this logic within the getServerSideProps isn't yielding the expected results. Can anyone offer guidance on how to resolve this issue?

Answer №1

It seems odd to me when using the await fetch with promises. Using await will result in the response being returned.

Perhaps you could experiment with:

const responseData = await fetch('/api/customers');
const customerData = await responseData.json();

Answer №2

  properties: {
        technology_resources: compressData(resources),
        user_data_summary: JSON.parse(JSON.stringify(subscriber_stats)), 
      }

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

Having trouble with state not updating correctly after making a fetch request within a useEffect hook in

In my React app with an Express backend, I am facing a challenge in updating the component state using the useEffect hook to trigger once when the component renders. Inside the useEffect, I fetch data from the Express server. const Favorites = ({ user }) = ...

Setting dynamic routes in Next.js when the basePath is not the root can be done by carefully configuring the routing system

After following a tutorial on setting up my Next.js project to be located in a subfolder (/app), everything was running smoothly. However, I encountered issues when trying to use dynamic routes for certain pages. I attempted three different approaches: ...

Is there a way to utilize jQuery's load function to fetch just a single element rather than the entire webpage?

I am looking to make a slight modification to the function so that it only loads the content of the colTwo div from the selected link on the menu, instead of loading the entire page. After checking out the code snippet on the jQuery website: $('#resu ...

When the user presses either the refresh button or the back button, they will be redirected

After the user presses refresh or uses the browser back button, I need to redirect them to a specific page in order to restart the application. My JavaScript code is as follows: var workIsDone = false; window.onbeforeunload = confirmBrowseAway; function ...

Is it possible to remove certain 'css-' class names that MUI automatically applies to its components? (Using Next JS and MUI)

After successfully migrating my create-react-app project to Next JS using the latest version (12.1.0) and following the migration guide at https://nextjs.org/docs/migrating/from-create-react-app, I encountered an unexpected issue. Despite still using MUI a ...

Unlimited scrolling: Fetching additional data via an Ajax request?

I am working on setting up a table with infinite scroll functionality to showcase user information such as name, address, and email. To accomplish this, I began by importing the json-server package and creating an API endpoint using fakerjs in a separate f ...

show the array as an image using the mean stack technology, which includes node.js and Angular

My persona has an attribute retrieved from MongoDB known as "faceDetection.photo", which is an array of values. Here is a snippet of the code: persona.faceDetection.photo=[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,1....etc] var encodedData = window.btoa( ...

The functionality of the webservice is not functioning properly

I'm currently working with Express and NodeJS to create a simple hello world webservice. I am attempting to call this webservice in ReactJS using Axios, but I am encountering issues with the response from the webservice. Below is my code for the webse ...

Making a REST call with values containing an apostrophe

Currently, I am utilizing REST and ajax to retrieve data from SharePoint using the URL below: https:xxxxxxxx/_vti_bin/ListData.svc/RMSD_Tasks?$orderby=IssueValue asc,StatusValue desc&$filter="+dropValue+" eq '"+secondFilterVal+"'&groupby ...

How to avoid an additional carriage return in Internet Explorer when editing a Textarea?

In Internet Explorer, we are facing an issue with a multiline textarea. After setting the content using JavaScript and checking it, everything appears correct without any additional carriage returns in the textarea: document.getElementById( 'text-ar ...

Storing data locally for a task management application

This is a standard to-do list. You can add or remove items, but the problem is that they disappear when you refresh. I thought about using localStorage to fix this issue. I successfully created an array to store the items. Now, my goal is to display the it ...

Dealing with callback errors: error handling is anticipated

In my Vue web application, I have enabled ESLint and encountered an issue with the following code: myApi.get('products/12').then((prodResponse) => { state.commit('ADD_PRODUCT', {product: prodResponse.data}) }, error => { cons ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Error: Unable to access the property 'map' as it is undefined | React, Redux

I'm encountering an issue that says: TypeError: Cannot read property 'map' of undefined. This error is related to trying to map over the array (posts) when it's empty: const postsList = posts.map((postList, i) => { Here is my actio ...

Send a file using ajax with the help of JavaScript and PHP

Currently, I am looking to implement a method for uploading files using Ajax and JavaScript/PHP without having the page refresh. My initial thought is to use Ajax to send the file using xmlhttp.send(file) and then retrieve it in the PHP script, but I' ...

Incorporate a new class into the direct parent element using Angular

I am facing a scenario where an element is dynamically assigned a class. My goal is to append a new class to its parent element only if the child element has a specific class. <a [ngclass]="addClassHere"> //need to add class here if child h ...

Turn off hover effect for the v-checkbox component in Vuetify 2

Is there a way to prevent the darkened circle from appearing behind a v-checkbox in Vuetify 2 when hovering over it? My v-checkbox is currently enclosed within a v-tab and a v-tooltip, although I'm not sure if that has any impact. <v-tab v-for=&quo ...

Jasmine: Methods for verifying if the accurate URL is invoked during a GET request

I need to test a service function, but I'm unsure how to mock an internal service function that is called within the main function. My goal is to verify if the correct URL is being accessed. Below is the code snippet for my service: angular.module(" ...

Strategies for updating arrays in Redux state

I am currently working on developing a project similar to "Trello" using react, redux, nodejs, and mongoDB. However, I have encountered an issue where when I add a card to a list, the redux state is not updated. As a result, I can only see the newly added ...

What causes AJAX to sometimes output with incorrect encoding?

After receiving a file from a server using AJAX (Angular), the file, a simple XLSX document, is sent as shown below: ob_start(); $file = \PHPExcel_IOFactory::createWriter($xls, 'Excel2007'); $file->save('php://output'); $respon ...