Encountering a PropertyTypeError while attempting to process a payment via Stripe in conjunction with use-shopping-cart on Next.js

Upon reaching the checkout page, I encounter the message:

Invalid value with type "undefined" was received for stripe. Valid type for stripe is "string".

This issue seems to be related to the redirectToCheckout function. Can someone assist me?

The cart-summary.tsx file displays all items, prices, and details fetched from sanity.io:

"use client"


import { useState } from "react"
import { Loader2 } from "lucide-react"
import { formatCurrencyString, useShoppingCart } from "use-shopping-cart"

import { Button } from "@/components/ui/button"

export function CartSummary() {

  const{ formattedTotalPrice, totalPrice, cartDetails, cartCount, redirectToCheckout } = useShoppingCart()
  const [loading, setLoading] = useState(false)
  const isDisabled =  loading || cartCount === 0
  const shippingAmount =  cartCount! > 0 ? 500 : 0
  const totalAmount = totalPrice! + shippingAmount


  async function onCheckout() {
    setLoading(true)
    const response = await fetch('/api/checkout', {
      method: "POST",
      body: JSON.stringify(cartDetails),
  })
  const data = await response.json()
  const result = await redirectToCheckout(data.id)
  if (result?.error) {
    console.error(result)
  }
  setLoading(false)
}

  return (
    <section
      aria-labelledby="summary-heading"
      className="mt-16 rounded-lg border-2 border-gray-200 bg-gray-50 px-4 py-6 shadow-md dark:border-gray-900 dark:bg-black sm:p-6 lg:col-span-5 lg:mt-0 lg:p-8"
    >
      <h2 id="summary-heading" className="text-lg font-medium">
        Order summary
      </h2>

      <dl className="mt-6 space-y-4">
        <div className="flex items-center justify-between">
          <dt className="text-sm">{formattedTotalPrice}</dt>
          <dd className="text-sm font-medium">Subtotal Amount</dd>
        </div>
      
        ... (additional code omitted for brevity) ...
 
    </section>
  )
}



The route.tsx file created for the checkout process resides in the api/checkout folder, where the necessary Stripe configurations are specified:

import { NextResponse } from "next/server"
// @ts-ignore
import { validateCartItems } from "use-shopping-cart/utilities"

import { inventory } from "@/config/inventory"
import { stripe } from "@/lib/stripe"

... (additional logic for handling POST request in checkout API) ...

I have attempted to debug this issue without success.

https://i.stack.imgur.com/K4tR1.png

https://i.stack.imgur.com/GC9N7.png

https://i.stack.imgur.com/ciguR.png

Answer №1

After reviewing the project tutorial, it appears that the error is related to the incorrect usage of the Stripe publishable key. To resolve this issue, navigate to the components folder and locate the file named providers.tsx. Ensure that your secret key is spelled correctly in this file.

"use client"

import { CartProvider } from "use-shopping-cart"

import { Toaster } from "@/components/ui/toaster"
import { TailwindIndicator } from "@/components/tailwind-indicator"
import { ThemeProvider } from "@/components/theme-provider"

interface Props {
  children: React.ReactNode
}

export function Providers({ children }: Props) {
  return (
    <CartProvider
      currency="CAD"
      shouldPersist
      cartMode="checkout-session"
      stripe={process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY!} // Verify that this value is correctly entered
    >
      <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
        <Toaster />
        {children}
        <TailwindIndicator />
      </ThemeProvider>
    </CartProvider>
  )
}

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

Leveraging RXJS for real-time response to keyboard and mouse click combinations in web

I am new to RXJS and looking for a way to drag an HtmlElement when the user presses the space key and then drags the element with the mouse. The dragging should be initiated by either pressing the SPACE key followed by a left click, or vice versa. The dra ...

Error message encountered: The object contains unknown key(s): 'images' at "experimental" - Error in Next.js version 14.1.0

Currently, I am in the process of deploying my nextJs project on github pages and following a tutorial. I encountered an issue while trying to execute a pipeline in github, receiving an error message. Below is the code snippet from my next.config.mjs fil ...

Warning: The gulp_jspm module is now deprecated and will be removed

Whenever I run gulp_jspm, a DeprecationWarning pops up. Is there an alternative method to generate my bundle files without encountering this warning? It seems like when I used gulp-jspm-build, I had to include some node files that were not necessary before ...

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...

What methods are available to keep a component in a fixed position on the window during certain scrolling intervals?

I need help creating a sidebar similar to the one on this Airbnb page. Does anyone have suggestions for how to make a component stay fixed until you scroll past a certain section of the page? I am working with functional React and Material-UI components, ...

Discovering and revising an item, delivering the complete object, in a recursive manner

After delving into recursion, I find myself at a crossroads where I struggle to return the entire object after making an update. Imagine you have an object with nested arrays containing keys specifying where you want to perform a value update... const tes ...

Ensuring proper extension of Request headers in Typescript

I am having trouble retrieving the userId from req.headers, how can I fix this issue? Initially, I attempted the following: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T& ...

In Angular 6, triggering a reset on a reactive form will activate all necessary validators

As a beginner in angular 6, I am currently facing an issue with resetting a form after submitting data. Although everything seems to be functioning properly, when I reset the form after successfully submitting data to the database, it triggers all the req ...

Encountered an issue with the property 'push' not being defined

Here's the schema for my mongoose model in JavaScript: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CartSchema = new Schema({ userID: String, items: [{ itemID: String, quantity: Number }] }); modul ...

Tips for Choosing a Tab in angular-ui: AngularJS

Is there a way to select the last tab without using ng-repeat? I want to avoid using ng-repeat but still need to select tabs. Any suggestions? If you'd like to see the code in action, you can visit: http://plnkr.co/edit/ZJNaAVDBrbr1JjooVMFj?p=preview ...

How to assign a global variable in Angular 2 from within a promise

I have encountered a strange issue while trying to assign a response to a global variable inside an observable. Here's the logic of my program: Fetch the latest playlists IDs from elastic search (using a type definition file for elastic search). T ...

Display one div and conceal all others

Currently, I am implementing a toggle effect using fadeIn and fadeOut methods upon clicking a button. The JavaScript function I have created for this purpose is as follows: function showHide(divId){ if (document.getElementById(divID).style.display == ...

Tips for accessing private variables

After running this code in nodejs, I noticed that the 'Count' becomes negative for large values of 'count'. It made me wonder, is it the fault of 'count' or 'chain'? What would be the best approach to modify the &apo ...

Using Angular UI Router to Access $scope Beyond the Scope of the UI View

Looking for a way to access $scope outside the UI view in my todo app. The structure is simple, with three panels as shown in this design For the full code, visit here I need to access the to-do detail on the third panel using $rootScope, which currently ...

Transform the size and convert an object from a picture into text based on the user's scrolling

I've been intrigued by the scrolling effects used on websites like Google SketchUp and Google Plus. It's fascinating how elements can transform as you scroll down the page. For example, on Google SketchUp's site, the banner starts off integr ...

Struggling to create an access token with the Slack API

My goal is to retrieve an access token from the Slack API. When I use the code provided below, it generates an authorization URL containing a temporary code in the query string. Once permissions are granted, the process redirects to /slack/oauthcallback. ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Trouble embedding iframes in local files?

I have recently created a file which includes the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <style> iframe { height: 500px; width: 600px; } ...

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Having trouble with retrieving API on nextjs 13 (application directory)?

I am encountering an issue while trying to retrieve data from a headless CMS (Strapi). The error message "Error: _hooks_useFetch__WEBPACK_IMPORTED_MODULE_2___default(...) is not a function" keeps popping up in Data.js. Can anyone assist me in understanding ...