Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message

ReferenceError: prisma is not defined
popped up. How can I resolve this?

import { NextApiRequest, NextApiResponse } from "next"
import { buffer } from "stream/consumers"
import Stripe from "stripe"

export const config = {
    api:{
        bodyParser: false
    }
}

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string,{
    apiVersion: '2023-10-16'
})

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
){

    const buf = await buffer(req)
    const sig = req.headers['stripe-signature']

    if(!sig){
        return res.status(400).send("Missing the stripe signature!")
    }

    let event: Stripe.Event

    try{
        event = stripe.webhooks.constructEvent(
            buf, sig, process.env.STRIPE_WEBHOOK_SECRET!
        )
    }catch(err){
        return res.status(400).send("Webhook error" + err)
    }

    switch(event.type){
        case 'charge.succeeded':
            const charge: any = event.data.object as Stripe.Charge;
            if(typeof charge.payment_intent === 'string'){
                await prisma?.order.update({
                    where: {paymentIntentId: charge.payment_intent},
                    data: {status: "complete", address: charge.shipping?.address},
                });
            }
            break;
        default:
            console.log("Unhandled event type:" + event.type)
    }
    res.json({received: true})
}

This is my current folder structure.

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

The following error has been identified:

Unhandled event type:payment_intent.succeeded
 ⨯ pages\api\stripe-webhook.ts (41:16) @ handler
 ⨯ ReferenceError: prisma is not defined
    at handler (webpack-internal:///(api)/./pages/api/stripe-webhook.ts:38:17)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {       
  page: '/api/stripe-webhook'
}
  39 |             const charge: any = event.data.object as Stripe.Charge;
  40 |             if(typeof charge.payment_intent === 'string'){
> 41 |                 await prisma?.order.update({
     |                ^
  42 |                     where: {paymentIntentId: charge.payment_intent},
  43 |                     data: {status: "complete", address: charge.shipping?.address}, 
  44 |                 });
 ○ Compiling /_error ...
 ✓ Compiled /_error in 2.7s (736 modules)

Answer №1

Your code is missing the necessary steps to import and instantiate Prisma.

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient();

For more details, refer to the quickstart documentation.

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

Can an error be thrown from a catch block within a Promise in a NodeJs environment?

While working with NextJs, I encountered an issue in my API code. In one of my api pages (/api/sendData.ts), there is a method call process() that belongs to a separate class platform.ts. This is the structure of my API code (in sendData.ts): try { pla ...

Utilizing Dynamic Route Parameters in Next.js

As a beginner in Next.js, I am currently working on setting up my routing system based on the documentation provided here. My file structuring is arranged as follows: pages/questions/[id].js I'm curious if there is a more efficient way to retrieve th ...

My goal is to implement a confirmation modal prior to any route changes within Next.js framework

Below is the code block that I have: const onRouteChangeStart = React.useCallback(() => { if (formState.isDirty) { if (window.confirm('Confirmation message')) { return true; } NProgress.done(); throw "A ...

Updating Next.js to React 18 is causing issues with my API calls that are being made using next-auth

Let me share an unusual situation with you. I am utilizing Next.js along with the Next-auth package for managing authentication. For this particular admin area, Server-Side rendering is not necessary. To authenticate users, I have devised a HOC to wrap a ...

Angular 12 is throwing an error due to the undefined @Input property

The issue presents a simple problem to comprehend yet proves challenging to resolve. There are 2 key components involved: CustomerComponent (Parent) InvoiceComponent (Child) Currently, I'm passing customer details using <admin-invoice-form [custo ...

Ways to Halt observable.timer in Angular 2

As I work on Angular2's Component, I am currently implementing the following functions: export class MypageEditComponent { ngOnInit() { this.timer = Observable.timer(100, 100); this.timer.subscribe(t => { this.setFormData(); } ...

Encountered an error: Object(...) does not conform to function standards in the handleChange method

When using JavaScript, everything works fine. However, when trying to implement TypeScript with the handleChange function, an error is consistently thrown whenever something is typed into the entries. The error message reads: "TypeError not captured: Objec ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: I suspect the issue lies in the import statement ...

The concept of a singleton design pattern is like a hidden treasure waiting to be

My approach to implementing the singleton pattern in a typescript ( version 2.1.6 ) class is as follows: export class NotificationsViewModel { private _myService: NotificationService; private _myArray: []; private static _instance: Notificatio ...

Encountered difficulties in deploying functions on Firebase Cloud Functions

While developing the Firebase Cloud Functions, I organized the files based on each function. Unfortunately, numerous errors occurred during deployment. Error [debug] [2022-07-19T14:36:17.677Z] <<< [apiv2][body] GET https://us.gcr.io/v2/xxxxxx/gcf ...

Best .htaccess configuration for optimizing Next.js static site generation

When exporting a static site using NextJS, the file structure includes: |-- index.html |-- article.html |-- tag.html |-- article | |-- somearticle.html | \-- anotherarticle.html \-- tag |-- tag1.html \-- tag2.html To hide the . ...

I'm receiving a 404 error on my API route in next.js - what could be causing this

What could be causing the error message "GET http://localhost:3000/api/db/getRideTypes 404 (Not Found)" when attempting to fetch data from the sanity client? Here is a snippet of code from Rideselector.js: //"use client"; import Image from &apo ...

The Next.js bundle analyzer is failing to generate pages for viewing bundles

I'm currently working on optimizing the bundle size of my website by utilizing https://www.npmjs.com/package/@next/bundle-analyzer However, when I execute npm analyze with "analyze": "cross-env ANALYZE=true next build", The HTML ...

Tips for showcasing additional details in error.tsx file within Next.js 14

Is there a way to show more detailed error information, such as error title, description, and cause in addition to just one sentence? I attempted to enhance the basic Error class by introducing two custom properties, but I am unable to access them in the ...

Error encountered in spyOn TS when passing array iteration instead of a string

Instead of repeating test cases with minor adjustments, I have implemented an Array and iterated through it. However, I am encountering a TS error in test when passed from the Array instead of as a string testLink Error: No overload matches this call. ...

Resolve the error message "variable is utilized prior to assignment"

Looking at the code snippet below, import { STS } from 'aws-sdk' const sts = new STS({ region: 'us-east-1' }); let accessKeyId: string let secretAccessKey: string sts.assumeRole(params, function(err, data) { if (err) { ...

Implement a concealed identification field with React-Admin within a React Native application

I'm currently working on incorporating the SimpleFormIterator from the React-Admin module in order to generate a list of child records within a parent record edit form. After setting up the SimpleFormIterator component with all the necessary details ...

Starting value within angular's toSignal()

Experiencing frustration with setting initialValue to true for a signal, encountering the error message (TS2769: No overload matches this call). The Observable does return an Observable. A workaround was found by omitting the "initialValue" option and ad ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

Utilizing a React hook within an event listener

I have developed a custom hook for playing audio in react, here is the code: "use client"; import { useEffect, useState } from "react"; export const useAudio = (url: string) => { const [audio, setAudio] = useState<HTMLAudioE ...