I decided to watch this video and I tried to follow the instructions:
Getting started with Next.js, TypeScript, and Stripe
1- My goal: create an e-commerce using graphcms (hygraph) to get the products and then buy them using stripe.
2- I started by just creating a button and redirecting the user to checkout session, but I couldn’t make it work.
When I click the checkout button I get this errors:
Uncaught (in promise) SyntaxError: Unexpected token '<’…
POST http://localhost:3000/api/checkout/session 404 Not Found

// I’m already using test Keys. I don’t think that’s the problem.
// src/pages/buy.tsx
import { loadStripe } from '@stripe/stripe-js';
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
export default function Buy () {
const handleClick = async (event: any) => {
event.preventDefault();
//POST <http://localhost:3000/api/checkout/session> 404 (Not Found)
//Uncaught (in promise) SyntaxError: Unexpected token '<'
// the html page returns 404 not found
const {sessionId} = await fetch('/api/checkout/session', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
quantity: 1
})
}).then(res => res.json());
const stripe = await stripePromise;
const { error } = await stripe!.redirectToCheckout({sessionId})
}
return (
<button type="submit" role="link" onClick={handleClick}>
Checkout
</button>
)
}
// src/pages/api/checkout/session.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { stripe } from '../../services/stripe';
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [{
price: process.env.PRICE_ID,
quantity: 1
},],
mode: 'payment',
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/checkout`,
})
res.status(200).json({ sessionId: session.id })
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method not allowed')
}
}
// src/services/stripe.ts
import Stripe from 'stripe';
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2022-08-01"
})
folder structure
