This content originally appeared on DEV Community and was authored by Michael Liendo
Use Case
- I want to display products in my web app that show the product's name, description and price. Similar to the below screenshot
I want to use the Stripe Dashboard as my source-of-truth.
Upon visiting my simple store, I would like my customers to receive the latest product information.
The Problem
I tried to fetch all the product data, but that didn't work since it doesn't contain the prices for those products.
I tried to fetch the price data, but the product field only contains an ID for the product and not the rest of the data.
🤔 "Do I really have to get all of my price data, then iterate over each price just to get the product data?"
Neither the Stripe Price docs or the Product docs address this use case. A quick google search confirmed my initial approach:
But for such a common task, it just wasn't sitting right with me.
@ibrahimcesar @stripe It's so odd that that how I would expect this to work by default isn't the case. Makes me think I'm overlooking something.20:42 PM - 18 Oct 2021
The Solution
Special shoutout goes to my buddy Nick (@dayhaysoos). He let me know that prices can use the expand parameter to get the corresponding product information.
After a quick search through the Stripe docs for "expand", the solution became clear:
import Stripe from 'stripe'
const Home = ({ productPriceData }) => {
console.log({ productPriceData })
return <div>display stripe data</div>
}
export async function getServerSideProps() {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)
const productPriceData = await stripe.prices.list({
expand: ['data.product'], // 🎉 Give me the product data too
})
console.log(JSON.stringify(productPriceData, null, 2))
return {
props: { productPriceData },
}
}
export default Home
🗒️ Quick Notes
- Expand can be used for just about any API call, but will only go 4 levels deep on what it returns.
- It's showcased here, but just to be clear, you can dig into an object with dot-notation:
data.product.nestedKey.nestedKey2 - I was going to use the
revalidatekey ingetStaticPropsto be cool, but then I realized that if a user refreshes the page, they should always see the correct price.
This content originally appeared on DEV Community and was authored by Michael Liendo
Michael Liendo | Sciencx (2021-10-19T06:52:04+00:00) Fetch both price and product data from stripe in a single api call. Retrieved from https://www.scien.cx/2021/10/19/fetch-both-price-and-product-data-from-stripe-in-a-single-api-call/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.

