The Next.js API has a mysterious parameter that remains undefined

I currently have a component implemented

import React, { useEffect } from "react";
import styles from "../styles/success.module.css";
import { useRouter } from "next/router";
import axios from "axios";
const Success = () => {
  const {
    query: { id },
  } = useRouter();

  useEffect(() => {
    fetchId();
  }, [id]);

  const fetchId = () => {
    axios
      .put("api/getOrder", {
        id,
      })
      .then((res) => {
        if (res.status === 200) {
          console.log(res.data.session);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div className={styles.success}>
      <h1>Thank you for your purchase {id}</h1>
    </div>
  );
};

export default Success;

In this code snippet, I am making an API request once the ID is loaded

const stripe = require('stripe')(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY);

export default async function handler(req, res) {
    const session = await stripe.checkout.sessions.retrieve(`${req.body.id}`)

    res.status(200).send({
        nessage: '200',
        session
    });
    res.status(500).send({
        message: '500'
    });
}

This is my backend setup and I dynamically assign an ID to the session variable. The issue arises when it initially appears as undefined, but ultimately fulfills the request.

The following represents the output displayed in my console:

error - StripeInvalidRequestError: No such checkout.session: undefined
    at Function.generate (C:\Users\user\Desktop\zigi\my-app\node_modules\stripe\lib\Error.js:40:16)
    ...
  
[Additional Details can be accessed via the link provided above]

Please provide assistance on how to rectify this situation. Thank you.

Answer №1

When not utilizing SSR in Next.js, the query parameter of useRouter() will be blank during prerendering.

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

How can I combine multiple requests in RxJS, executing one request at a time in parallel, and receiving a single combined result?

For instance, assume I have 2 API services that return data in the form of Observables. function add(row) { let r = Math.ceil(Math.random() * 2000); let k = row + 1; return timer(r).pipe(mapTo(k)); } function multiple(row) { let r = Math.c ...

Error in unit testing: Trying to access property 'pipe' of an undefined variable results in a TypeError

Recently, I've been faced with the challenge of writing a unit test for one of the functions in my component. The specific function in question is called 'setup', which internally calls another function named 'additionalSetup'. In ...

What is the proper way to define an array of objects in TypeScript?

In search of a way to define a function that accepts an array of unspecified object types, known as "anonymous types." I want to enforce strict typing with TypeScript. The objects in the array all have properties like name, price, and description. bagTotal ...

Step-by-step guide: Logging into next js with auth0

Having trouble logging in to a Next.js app with Auth0? I followed the quickstart guide on the Auth0 website, but I'm encountering an error on the login page. <a href="/api/auth/login">Login</a> This is pages/api/[...auth0].js i ...

The Angular-slickgrid is encountering an issue where it is unable to access the property "hostView" as it

Hey there developers, I've been experimenting with the angular slickgrid library and attempting to incorporate the rowDetailView feature it offers. The issue I'm facing is that while I can expand the view by clicking on it, I'm unable to c ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

Converting Data Types in Typescript

So I'm working with Data retrieved from a C# Rest Server. One of the values in the array is of type Date. When I try to perform calculations on it, like this: let difference = date1.getTime() - date2.getTime(); I encounter the following error messag ...

The operation of assigning the value to the property 'baseUrl' of an undefined object cannot be executed

I recently created a JavaScript client using NSWAG from an ASP .NET Rest API. However, I am encountering some errors when attempting to call an API method. The specific error message I am receiving is: TypeError: Cannot set property 'baseUrl' of ...

utilizing React.js, learn how to extract the most recent user input and store it within an array

My Input component generates input tags dynamically based on JSON data. I've implemented the onChange method in the input tag, which triggers a function called "handleChange" using contextAPI to record the values in another component. The issue aris ...

What is the distinction between revealing environment variables in Next.js using the next.config.js as opposed to utilizing the NEXT_PUBLIC prefix?

As stated in the nextjs documentation, to make my environment variables accessible in the browser, I can simply prepend them with NEXT_PUBLIC in my .env.local file, like this: NEXT_PUBLIC_VAR=7 However, it seems that another approach is available where I ...

Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code: const { NETWORK } = require(`${basePath}/constants/network.js`); The content of network.js file is as follows: export ...

Tips for creating Material UI elements using React and Typescript

I am looking to extend a component from the Material UI library by creating a custom component that encapsulates specific styles, such as for a modal wrapper. However, I feel that my current solution involving the props interface may not be ideal. Is the ...

Navigate to the logout page automatically when closing the final tab

In order to comply with the requirement, I need to log out the user when they close the last tab on the browser. ngOnInit() { let counter: any = this.cookieService.get('screenCounterCookie'); counter ? ++counter : (counter = & ...

Is the TypeScript compiler neglecting the tsconfig.json file?

I am new to TypeScript and currently exploring how to set it up in WebStorm. One of the first steps I took was creating a tsconfig.json file in the main directory of my project and updating the built-in TypeScript compiler to version 1.6.2. However, despit ...

The error message "React is not defined" is commonly encountered when using React Native Storybook with

While attempting to configure React Native with Storybook, I encountered an issue when importing a .tsx component. The error displayed was: React is not defined ...

How can I get the class name of the drop destination with react-dnd?

Imagine having this component that serves as a drop target module. import { useDrop } from 'react-dnd'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function Draggable ...

What are the steps to save information to Firebase's Realtime Database?

Currently, I am facing an issue where user location data is not being written into our Firebase Realtime Database even though the console confirms that the data is fetched correctly every 2 seconds. I am seeking assistance on how to resolve this problem. ...

The Vue property I customized in my component is not being recognized by VSCode(Vetur)

I've successfully implemented a plugin in Vue by declaring it in a main.ts file, defining its type in a plugin.d.ts file, and utilizing it in a component.vue file. Although the compilation is error-free, I am encountering an issue with VSCode intellis ...

The getServerSession() method in NextAuth fails to retrieve all of the user fields when called in an API route

I am currently working on implementing an API route where I need to verify the user's authentication status and check if they are an admin. As part of this process, I attempted to utilize the getServerSession method, however, it returned a session wit ...

Limiting the assignment of type solely based on its own type, without considering the components of the type

I have defined two distinct types: type FooId = string type BarId = string These types are used to indicate the specific type of string expected in various scenarios. Despite TypeScript's flexibility, it is still possible to perform these assignment ...