I’m having an issue where my Stripe payment verification works fine locally, but when deployed, I encounter a CORS error. The payment goes through, and I can see a 200 OK response in the console, but I’m unable to verify the payment due to a network error.
Context:
I have a Stripe integration where users can purchase credits using the payment flow. Upon successful payment, it redirects the user to a Success page, where I verify the Stripe session using the session ID.
The verification works as expected locally—no issues, no errors. However, in the deployed version, I get the following error:
Failed to verify payment. Error: Network not found
In the browser console, I see a CORS error related to the payment verification request.
Backend Code (Controller):
Below is the code where I create the Stripe session on the backend. This part works fine; the payment gets processed, and the user is redirected to the Success page with a session ID:
const stripeSession = async (req: IAuthRequest, res: Response) => {
const { creditPackageId } = req.body;
const userId = req.user?._id;
if (!userId) return res.status(400).json({ error: `User ID is required` });
const selectedPackage = creditPackages.find(
(pkg) => pkg.id === creditPackageId,
);
if (!selectedPackage) {
return res.status(400).json({ error: 'Invalid credit package' });
}
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'eur',
product_data: {
name: selectedPackage.name,
description: `Purchase ${selectedPackage.credits} credits`,
},
unit_amount: selectedPackage.price * 100,
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.FRONTEND_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.FRONTEND_URL}/cancel`,
metadata: {
userId: userId.toString(),
creditPackage: selectedPackage.name,
credits: selectedPackage.credits.toString(),
amount: selectedPackage.price.toString(),
},
});
res.json({ url: session.url });
} catch (error) {
if (error instanceof Error) {
console.error('Error retrieving checkout session:', error.message);
res.status(500).json({ error: 'Error retrieving checkout session' });
} else {
console.error('Unexpected error:', error);
res.status(500).send('An unexpected error occurred');
}
}
};
Frontend Code:
On the frontend, after the payment is successful, I redirect the user to the Success page, where I verify the session ID:
import { useEffect, useState } from 'react';
import axios from 'axios';
import { baseUrl } from '../utils/static-data/URLs/baseUrl';
import { useSearchParams } from 'react-router-dom';
import PaymentStatus from '../components/PaymentStatus';
import Loader from '../components/Loader';
const Success = () => {
const [searchParams] = useSearchParams();
const sessionId = searchParams.get('session_id');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const verifySession = async () => {
const token = `Bearer ${localStorage.getItem('authToken')}`;
try {
await axios.get(`${baseUrl}/payment/stripe/verify`, {
params: { session_id: sessionId },
headers: {
Authorization: token,
},
});
} catch (err: any) {
setError(`Failed to verify payment. Error: ${err.message}`);
} finally {
setLoading(false);
}
};
if (sessionId) {
verifySession();
}
}, [sessionId]);
if (loading) return <Loader text="Loading ..." />;
if (error) return <p>{error}</p>;
return (
<div>
<PaymentStatus status={'success'} />
</div>
);
};
export default Success;
Issue:
Locally, everything works fine. The payment completes, and the session verification passes without any issues.
On the deployed version, the payment still goes through successfully, but I get a CORS error when trying to verify the session ID. The console shows a Network not found error, and the browser blocks the request due to CORS.
What I Have Tried:
Verified the backend is correctly configured for CORS.
The authorization token is being sent correctly in the headers.
Questions:
- What could be causing this CORS issue only in the deployed version, and how can I resolve it?
- Could there be something in the deployment environment (e.g., server configuration, headers, or domains) that is causing this?
- Any suggestions on what I can check or change to fix the CORS issue?
Md. Shakhawat Mamun is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2