0

The code works properly and redirects to the stripe checkout page but after deployment, it doesn't. I'm getting the status 500 when trying to checkout but the cart items and amount get posted in stripe logs with the status unpaid.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:387:5) at ServerResponse.setHeader (node:_http_outgoing:603:11) at NodeNextResponse.setHeader (C:\Users\subash\OneDrive\Desktop\ecommerce\ecommerce\node_modules\next\dist\server\base-http\node.js:56:19)

Here's the code

lib/getStripe.js

import {loadStripe} from '@stripe/stripe-js';

let stripePromise;

const getStripe = () => {
    if(!stripePromise){
        stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
    }
    return stripePromise;
}

export default getStripe;

cart.js

const handleCheckout = async () => {
    const stripe = await getStripe();

    const response = await fetch('/api/stripe', {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(cartItems)
    });

    if (response.statusCode === 500) return;
    const data = await response.json();

    toast.loading("Redirecting...");
    stripe.redirectToCheckout({ sessionId: data.id });
  };

pages/api/stripe.js

import Stripe from 'stripe';

const stripe = new Stripe(process.env.NEXT_PUBLIC_STRIPE_SECRET_KEY);

export default async function handler(req, res) {
  if (req.method === 'POST') {
    
    try {
      // Create Checkout Sessions from body params.
      const params = {
        submit_type :'pay',
        mode:'payment',
        payment_method_types:['card'],
        shipping_address_collection: {
            allowed_countries: ['IN'],
        },
        shipping_options: [
            {shipping_rate: '...'}
        ],
        line_items: req.body.map((item)=>{
            const img = item.image[0].asset._ref;
            const newImage = img.replace('image-','https://cdn.sanity.io/..../').replace('-webp','.webp');
            return {
                price_data:{
                    currency:'inr',
                    product_data:{
                        name:item.name,
                        images:[newImage],
                    },
                    unit_amount:item.price*100,
                },
                adjustable_quantity:{
                    enabled:true,
                    minimum:1
                },
                quantity:item.quantity
            }
        }),
        success_url: `${req.headers.origin}/success`,
        cancel_url: `${req.headers.origin}`,
      }
      const session = await stripe.checkout.sessions.create(params);

      res.status(200).json(session);
      res.redirect(303, session.url);
    } catch (err) {
      res.status(err.statusCode || 500).json(err.message);
    }
  } else {
    res.setHeader('Allow', 'POST');
    console.log("error");
    res.status(405).end('Method Not Allowed');
  }
}
2
  • What are You getting as a response? Check the network tab in chrome dev tools. developer.chrome.com/docs/devtools/network/#load Commented Oct 18, 2022 at 9:36
  • Basically you will get this error when you send a response from the server and then try to send another response Commented Oct 18, 2022 at 15:20

1 Answer 1

1

You're still using the legacy Checkout integration with redirectToCheckout instead you should look at the new integration path for Next.js that you can find here. If you want more info about migrating from the legacy integration you can check the Checkout migration guide here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.