0

I want to create a checkout form with stripe using api and nextjs.
Documentation https://stripe.com/docs/api/checkout/sessions/create?lang=node

const stripe = require('stripe')('');

const session = await stripe.checkout.sessions.create({
  success_url: 'https://example.com/success',
  cancel_url: 'https://example.com/cancel',
  line_items: [
    {price: 'price_H5ggYwtDq4fbrJ', quantity: 2},
  ],
  mode: 'payment',
});

when i run the code I get the following : enter image description here enter image description here I also tried https://stackoverflow.com/a/74095665/18355976

like who
  • 111
  • 2
  • 12
  • What is your node version? I believe Top level await shipped enabled by default in >=v18 – Yasio Oct 20 '22 at 20:54
  • Does this answer your question: [how can I use top level "await" in typescript next.js](https://stackoverflow.com/questions/68339243/how-can-i-use-top-level-await-in-typescript-next-js)? – juliomalves Oct 22 '22 at 12:12

2 Answers2

0

You are supposed to have this code directly in a route. Not in the racine of the file

boubaks
  • 352
  • 2
  • 8
0

The await keyword needs to be used inside an async function.

NextJS API routes are required to export a function that gets called when the API route is requested. This can be an async function to allow you to use await inside it.

Example from the documentation:

export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe' })
}

Example with your code:

// pages/api/stripe.js

const stripe = require('stripe')('');

export default async function handler(req, res) {
  const session = await stripe.checkout.sessions.create({
    success_url: 'https://example.com/success',
    cancel_url: 'https://example.com/cancel',
    line_items: [
      {price: 'price_H5ggYwtDq4fbrJ', quantity: 2},
    ],
    mode: 'payment',
  });

  // Do stuff

  // Send back a response
  res.status(200).json({ name: 'John Doe' })
}

NextJS API Routes Documentation

LongLegJim
  • 262
  • 1
  • 5