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

Tips for placing breakpoints in a NextJS application

I'm currently working with nextjs and I'm struggling to find the right place to set breakpoints in my browser. When I use Chrome dev tools and expand sv.moxne.net (my development domain), all I see is what appears to be compiled assets instead o ...

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 ...

Nextjs export functionality is not displaying the 404 page

After adding a custom 404.js file in the /pages directory, it worked fine locally. However, upon running next export and transferring all files from the output directory to the public_html directory in cPanel, everything seemed to be working well except fo ...

Learn the steps to access localStorage data prior to client-side rendering with Next.js

For the past 3 days, I have been struggling with a strange warning while using react + next.js on the client side. The warning seems to be related to the isUserAuthenticated value stored in localStorage. Since localStorage is only accessible on the client ...

How to iterate through the elements of an object within an array using Vue.js and TypeScript

There was an issue with rendering the form due to a TypeError: Cannot read properties of undefined (reading '0'). This error occurred at line 190 in the code for form1.vue. The error is also caught as a promise rejection. Error Occurred <inpu ...

Alternative method for handling web requests in case JavaScript is not enabled

Issue: i) I am developing a JSF2 application and need to implement a tab control on a page. When a user clicks on a tab, the content for the panel below should be loaded from an xhtml file on the server using an ajax call. ii) I want this functionality ...

When using $resource.save, it returns a "Resource" instead of just an ID

For some reason, I am struggling with a seemingly simple task and cannot find a solution by going through documentation or other Angular related questions on SO. I may not be the brightest, so I could really use some help here as I am feeling stuck. Take ...

Creating a modal popup when a button is clicked

After searching online for a way to make my sign up modal pop up when the signup button in my navbar is pressed, I was unable to find any information on how to achieve this. I suspect it involves JavaScript, but my knowledge of JS is limited. I attempted ...

Angular 15 brings an exciting new feature: the Swiper 9 Element

I went through the swiperjs official documentation found at: swiperjs doc To display images, I created a method to configure and initialize the swiper only when necessary. Below is the HTML code snippet: <swiper-container #swiperRef init="false& ...

Have you noticed the issue with Angular's logical OR when using it in the option attribute? It seems that when [(ngModel)] is applied within a select element, the [selected] attribute is unable to change

Within the select element, I have an option set up like this: <option [selected]=" impulse === 10 || isTraining " value="10">10</option> My assumption was that when any value is assigned to impulse and isTraining is set to true, the current o ...

In Next.js, anchor links do not smoothly scroll between pages

Within my nextjs project, I have implemented a navigation menu within the header. This menu consists of links like /#apartments, /#reviews, and /#contact-us. Each of these links directs users to the main landing page at /, with unique hash values that allo ...

Creating dynamic captions in an Angular grid is an essential feature for enhancing the

Is there a way in Angular to dynamically update the grid titles based on an array of elements in the model? How can I display them as captions? For instance, imagine we are currently in week 202010. I would like to automatically generate the next five wee ...

When utilizing jade.compile for compiling a jade template containing mixins or included partials

I'm currently exploring solutions for this challenge. The issue at hand involves compiling a jade template for an email campaign, but the file I am attempting to compile is a mixin that includes some partials. Here's an example: controllers/us ...

Transporting a Typescript file to the customer using JavaScript

As a newcomer to typescript and in the process of creating a small application in visual studio 2013, I have noticed that when viewing the project in Chrome's developer tools, typescript files (*.ts) are being downloaded to the client. This could pote ...

Ways to display a variable within an HTML element

What could be causing variable a to be undefined? export default function Surah() { let a; const updateVariable = (id) => { a = id; console.log(a); }; return ( <div> <div> <button onClick={() => ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

Arranging an array of objects by their alphanumeric string property values

Currently, I am facing an issue with sorting an array of objects in TypeScript. The structure of my array is as follows: [ { "title": "Picture3.jpg", "targetRange": "B2", "type": ...

The initial loading of jQuery DataTables shows duplicate entries

Expanding on my query from the previous day: jQuery AJAX call function on timeout Following the guidance provided in the response from yesterday's post, the table successfully reloads without requiring a full page refresh every 30 seconds. However, ...

Error: The componentwillmount function has encountered an issue. Actions must be in the form of plain objects. For asynchronous actions, consider

Currently, I am setting up a feature to retrieve all images based on their type using redux-saga. There are two types available: kristik and motif. While implementing the kristik type, everything works smoothly and I receive successful responses. However, ...

Learn how to execute shell commands on a Linux server from a Node.js application by utilizing Socket.io for establishing a connection. This includes tasks such as running "ls -ltr", changing

After successfully establishing a connection with my Linux server, I aim to execute shell commands for automation purposes such as changing directories and creating new folders. The main objective is to connect to the Linux server through a webpage, wher ...