I am integrating Stripe payment processing into my React application using Vite, Fastify, and Stripe. However, I am encountering a 404 error when trying to create a payment intent using the /api/create-payment-intent endpoint with Render address.
——vite.config.js——
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import dotenv from "dotenv";
dotenv.config();
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
port: 4242,
proxy: {
// string shorthand
// with options
"/api": {
target: process.env.VITE_RENDER_HOST || "http://localhost:5252",
changeOrigin: true,
rewrite: (path) => path.replace(/^/api/, ""),
},
},
},
});
——server.js——
require("dotenv").config();
// Require the framework and instantiate it
const fastify = require("fastify")({ logger: true });
const stripe = require("stripe")(`${process.env.VITE_STRIPE_SECRET_KEY}`);
// Fetch the publishable key to initialize Stripe.js
fastify.get("/publishable-key", () => {
return { publishable_key: `${process.env.VITE_STRIPE_PUBLISHABLE_KEY}` };
});
// Create a payment inntenttent and return its client secret
fastify.post("/create-payment-intent", async (req, res) => {
const { amount } = req.body;
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency: "usd",
payment_method_types: ["card"],
});
return { client_secret: paymentIntent.client_secret };
});
// Run the server
const start = async () => {
try {
await fastify.listen({ port: 5252 });
console.log("Server listening ... ");
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
------checkout.jsx-------
const Checkout = () => {
const setPriceState = useRecoilValue(priceState);
const totalPriceState = parseFloat((setPriceState * 100).toFixed(2));
const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY);
const [clientSecretSettings, setClientSecretSettings] = useState({
clientSecret: "",
loading: true,
});
useEffect(() => {
async function createPaymentIntent() {
const response = await axios.post("/api/create-payment-intent", {
amount: totalPriceState,
});
setClientSecretSettings({
clientSecret: response.data.client_secret,
loading: false,
});
}
createPaymentIntent();
}, []);
When using localhost, Stripe works fine. However, if I add target: process.env.VITE_RENDER_HOST || “http://localhost:5252”, I get a 403 error. Is there any documentation on how to connect Render with Stripe? I can’t seem to find it anywhere.
hehehad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.