How can I retrieve a value from my Node.js backend in a JavaScript frontend?

I’m looking to fetch a value from my Node.js backend within a JavaScript file.
Here is the backend code snippet:

(async () => { const orderSession = await stripe.checkout.sessions.create({ payment_method_types: [‘card’], line_items: [{ name: ‘T-shirt’, description: ‘Comfortable cotton t-shirt’, images: [‘https://example.com/t-shirt.png’], amount: 500, currency: ‘eur’, quantity: ((req.body.tickets - 0) + (req.body.tickets_kid - 0)), }], success_url: ‘http://localhost:3000/thank-you?session_id={orderSession.id}’, cancel_url: ‘https://localhost:3000/tickets’, }); res.send(orderSession); })();

And here’s my frontend code:
const stripeClient = Stripe(‘secretkey’); const orderSession = ? console.log(orderSession); async function initiateCheckout() { console.log(‘Checkout initiated’); const { error } = await stripeClient.redirectToCheckout({ sessionId: ‘{{orderSession.id}}’ }); window.alert(error.message); };

I’m attempting to pass the session ID to the JavaScript file. Any assistance would be appreciated.

You might consider using socket.io to push data from your backend to the frontend in real-time. This way, once your server has the orderSession, it can emit the session ID to your frontend as soon as it’s available. This can simplify asynchronous operations and help maintain a real-time connection.

To retrieve the value from your Node.js backend to your frontend, you’ll need to use an HTTP request. Your backend must be capable of handling a route where it sends back the session data. Assuming you are using Express.js, set up a separate endpoint to handle this data provision. On the frontend, use fetch or an equivalent AJAX method to send a request to this endpoint and retrieve the session ID. Replace orderSession.id in the redirectToCheckout method with sessionData.id variables you receive from the response. This will ensure your frontend receives the backend session ID correctly.