For enquiries call:



HomeBlogWeb DevelopmentHow to Integrate Stripe Payment Gateway in Node.js App

How to Integrate Stripe Payment Gateway in Node.js App

28th Sep, 2023
view count loader
Read it in
13 Mins
In this article
    How to Integrate Stripe Payment Gateway in Node.js App

    In this article, you’ll learn how to integrate Stripe Payments into your Node.js application. You’ll set up a sample web application using React and Express. If you’re looking to enter the world of Web Development, you can enroll in our course to learn Node.js with us. This article is helpful for those who are looking to integrate payments into their Node.js applications.

    Steps to Integrate Stripe Payments in Node.js App

    Payment gateways make it easier for you to integrate payments into your app and for users to pay through it. There are multiple payment gateways in the market, including Paytm, Razorpay, and others. But Stripe is one of the most often used gateways. Stripe's software and APIs are used by millions of companies, from small startups to major corporations, to collect payments, send payouts, and manage their businesses online. Not only does Stripe help with payment, but also helps you to send invoices to your customers after the payments using Stripe invoice. 

    It is pretty easy to set up Stripe in your app. You just need to create your account on Stripe and get the secret access keys. Then, you’re ready to use their API to process payments. In addition to production, they provide you with test credentials to test your payment flow. Stripe has very clean API documentation to get started. In this article, we’ll use React and Node.js to create our application and integrate Stripe payments into it. Explore our Full Stack Developer Course to work on similar live projects while learning.

    Before getting started, make sure you have Node.js installed in your system. Alternatively, you can install it from here. 

    1. Create Stripe Account

    In order to use Stripe, you need to register yourself on Stripe.

    If you have already registered, you can sign in using the link below Create Account button.  

    Stripe Requirements  

    Once you sign in to your Stripe account, you may be required to go through some necessary steps in order to activate payments. Make sure you go through it. After you’re done, you’ll be redirected to the Stripe Dashboard similar to below. 

    On the top left of the dashboard, you’ll find an option to create a new account. Click on New Account, add your Account Name and Country of Operation and click on Create account.  

    Once you create a new account, you’ll be required to activate the payments again for this account.  

    2. Get Tokens

    Once you’re done with all the steps mentioned above, click on the Developers button on the top-right of the dashboard. Then click on the API Keys to go to the page where you’ll get your Standard Keys to authenticate API requests. 

    These keys are test data and cannot be used in actual payments. Once you activate your account, you can enable live keys as well. 

    3. Setting up the Node.js Server 

    Before jumping to the front-end, you’re going to create the Node.js server that will interact with Stripe and handle the payments. For the sake of simplicity, we’ll use as few dependencies as required. The dependencies required for the backend are as follows: 

    • cors: You’ll require cors middleware because you will be making requests to the Stripe server. 
    • express: You’ll use express to create the backend server. 
    • stripe: The stripe npm dependency will help you access the Stripe API from your server. 
    • dotenv: This dependency will help you manage your environment variables and store your secret keys. 
    • nodemon: This dependency automatically restarts the Node.js application when file changes are detected in the directory. 

    While you’ll create a simple application in this article, you can create a far better web application as you learn Node.js at KnowledgeHut.

    Project Initialization

    Before getting started, create a folder named backend, where you can store all your backend code right here. Now, fire up your terminal in this directory and follow along. 

    To create a Node project, use the below command: 

    >> npm init 

    It will ask you for some details, which are not that important for the sake of this article. 

    After you’re done, you will find a package.json file in your backend directory. Now, open this directory in your favorite code editor and create a file named index.js inside it. Make sure the filename is the same as the entry point you have set during the project initialization. 

    Now, use the command below to install all the dependencies mentioned above: 

    >> npm i cors express stripe dotenv nodemon 

    Let us also add the script to start the Node.js server in the package.json file. 

      "description""Sample backend server for integrating Stripe payments", 
      "scripts": { 
        "start""nodemon index.js" 
      "author""Ashutosh Krishna", 
      "dependencies": { 

    Now, create a file named .env where you will store your secret keys. The contents of the file should be similar to the below: 


    We can load these environment variables using the dotenv dependency and then access them as process.env.KEY_NAME. 

    4. Create the Server  

    Now let us create our server in the index.js file. 

    In the script below, we’ll import the required dependencies first. Then, create an app using express. The required middleware is also defined. A sample route is created, which just responds with a Hello World message. The server listens on port 8000. 

    Notice how we load the environment variables using the dotenv dependency and used them. 

    const cors = require("cors"); 
    const express = require("express"); 
    const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); 
    const app = express(); 
    // Middlewares here 
    // Routes here 
    app.get("/", (req, res) => { 
      res.send("Hello World"); 
    // Listen 
    app.listen(8000, () => { 
      console.log("Server started at port 8000"); 

    Once you run the server using the npm start command, you can go to http://localhost:8000 on your browser, and you will find your Hello World message there. 

    Now you need a POST route that can be hit by the front-end. In this route, you’ll create a customer and will charge the amount. Let us create this route now."/api/create-checkout-session"async (req, res) => { 
      const { product } = req.body; 
      const session = await stripe.checkout.sessions.create({ 
        payment_method_types: ["card"], 
        line_items: [ 
            price_data: { 
              currency: "inr", 
              product_data: { 
              unit_amount: product.price * 100, 
            quantity: product.quantity, 
        mode: "payment", 
        success_url: "http://localhost:3000/success", 
        cancel_url: "http://localhost:3000/cancel", 
      res.json({ id: }); 

    In the above script, an asynchronous “/api/create-session-checkout” POST route is created. Inside the function, the product is fetched from the request's body. This product shall be passed from the front end. Next, you’re creating a Stripe checkout session where you declare the payment method type as card, the price and product details, the mode, and the success and cancel URLs. You can add more details about the product if you wish to. Refer to the Stripe documentation to learn more about this. The function responds with an id, that is, the session's id. This id is used by Stripe later. That’s pretty much about the backend part of our application. 

    5. Code Setup - Create React App  

    Now that you have a backend server ready, it’s time to create a React app that can make use of the backend server. When you install npm, you get npx too. For the sake of the article, you’re going to create a React app named frontend. To create a React app, you can use the below command: 

    >> npx create-react-app frontend 

    The command will set up a sample React app. To see if the setup is working fine, you can run the npm start command. If you see the below output, your setup is ready. 

    Installing dependencies  

    Now, before you start working on the front-end of the application, you need to install a few dependencies here too. They are: 

    • react-router-dom: This dependency is used to create single-page applications, and will help you in routing. 
    • @stripe/stripe-js: This dependency helps you use Stripe.js as an ES module.  
    • react-bootstrap: This is an optional dependency you’re going to use for styling your application using Bootstrap. 

    Now, as always, to install the above-mentioned dependencies, you need to run the following command: 

    >> npm i react-router-dom @stripe/stripe-js react-bootstrap 

    6. Setting Up the Frontend 

    Here comes the main frontend task now. You’re going to create three components - one for the checkout page where you’ll have a simple product card with a pay button, one for the success page and the final one for the cancel page. These all components will be present inside a components directory inside the src folder.  

    Checkout Page 

    Inside the components directory, create a file named StripePayment.js. Let us import all the dependencies we’d be using in the component: 

    import React, { useState } from "react"; 
    import "bootstrap/dist/css/bootstrap.min.css"; 
    import Button from "react-bootstrap/Button"; 
    import Card from "react-bootstrap/Card"; 
    import { loadStripe } from "@stripe/stripe-js"; 

    Now, create an empty function called StripePayment and export it as below: 

    function StripePayment() { 
    export default StripePayment; 

    Now, we will require something to buy. Let us create a simple product with few details in the function as below: 

    function StripePayment() { 
      const [product, setProduct] = useState({ 
        name: "Go FullStack with KnowledgeHut", 
        price: 1000, 
        productOwner: "KnowledgeHut", 
        description: "This beginner-friendly Full-Stack Web Development Course is offered online in blended learning mode, and also in an on-demand self-paced format.", 
        quantity: 1, 
    export default StripePayment; 

    To create a product, we have used the useState() function. The product contains few details such as name, price, productOwner, description and quantity. Now, let us create a product card using react-bootstrap inside the function.  

    import React, { useState } from "react"; 
    import "bootstrap/dist/css/bootstrap.min.css"; 
    import Button from "react-bootstrap/Button"; 
    import Card from "react-bootstrap/Card"; 
    function StripePayment() { 
      const [product, setProduct] = useState({ 
        name: "Go FullStack with KnowledgeHut", 
        price: 1000, 
        productOwner: "KnowledgeHut", 
          "This beginner-friendly Full-Stack Web Development Course is offered online in blended learning mode, and also in an on-demand self-paced format.", 
        quantity: 1, 
      return ( 
        <Card style={{ width: "20rem" }}> 
            variant="top" src="" 
            <Button variant="primary" onClick={makePayment}> 
              Buy Now for {product.price} 
    export default StripePayment; 

    The above script is pretty easy to understand where you have created a Bootstrap card with top-image, card title, card body text and a button. We have also added an onClick parameter on the button, which calls a makePayment function. Let us create the makePayment function now. 

    const makePayment = async () => { 
        const stripe = await loadStripe("your-publishable-key"); 
        const body = { product }; 
        const headers = { 
        const response = await fetch( 
            method: "POST", 
            headers: headers, 
            body: JSON.stringify(body), 
        const session = await response.json(); 
        const result = stripe.redirectToCheckout({ 
        if (result.error) { 

    The makePayment is an asynchronous function that makes requests to our backend server. An instance of Stripe is loaded using the loadStripe function. The product is added in the body of the request. Do you remember we sent a session id in the response from the backend? This session id is then extracted from the response and provided to the redirectToCheckout function from the stripe dependency.  

    Success and Cancel Pages

    In addition to the checkout page, you’ll create two other pages for success and canceled transactions. Inside the components directory, create two files - Success.js and Cancel.js. 

    import React from "react"; 
    function Success() { 
      return ( 
          <h2>Thanks for your order!</h2> 
          <h4>Your payment is successful.</h4> 
            We appreciate your business! If you have any questions, please email us 
            <a href=""></a>. 
    export default Success; 
    import React from "react"; 
    function Cancel() { 
      return ( 
          <h4>Oops! Your payment has been cancelled.</h4> 
            We appreciate your business! If you have any questions, please email us 
            <a href=""></a>. 
            <button> Go to Home page</button> 
    export default Cancel; 

    Routing the Components   

    Now that all the components are ready, you’ll need to route them as below: 

    • “/” : Checkout Page 
    • “/success” : Success Page 
    • “/cancel” : Cancel Page 

    To route the pages, you’re going to use react-router-dom as below: 

    import React from "react"; 
    import { BrowserRouter, Routes, Route } from "react-router-dom"; 
    import StripePayment from "./components/StripePayment"; 
    import Success from "./components/Success"; 
    import Cancel from "./components/Cancel"; 
    function App() { 
      return ( 
            <Route path="/success" element={<Success />} /> 
            <Route path="/cancel" element={<Cancel />} /> 
            <Route path="/" element={<StripePayment />} /> 
    export default App; 

    With this, the frontend of the application is ready too. It might not look that good, but it fulfills its purpose. You can run your backend and frontend of the application using the npm start command. 

    7. Test Card Details

    In order to test your integration, you’re not going to use real cards for sure. To help you with this, Stripe provides you with test cards. 

    Test cards let you simulate several scenarios: 

    • Successful payments by card brand or country 
    • Card errors due to declines, fraud, or invalid data 
    • Disputes and refunds 
    • Authentication with 3D Secure and PINs 

    The test cards can only be used when you’re using Stripe Test Keys. You can find a lot of cards on this page. 

    Looking to level up your coding skills? Join our Python course training and unlock endless possibilities. From web development to data analysis, Python is the language of the future. Don't miss out on this opportunity to become a Python pro!


    In this article, you learned how to integrate Stripe payment gateway into your Node.js application. You created a sample React Application and a Node.js server to interact with Stripe APIs. This was a very basic example of payment integration. Stripe supports many more features such as Subscription, Recurring Payments, etc. 

    Frequently Asked Questions (FAQs)

    1How do you integrate Stripe payment gateway in React JS?

    Stripe provides you with a dependency called @stripe/stripe-js that helps you use Stripe.js as an ES module. You need to have a backend server to interact with Stripe APIs. In addition to that, there are several third-party dependencies available on too, that can help you integrate Stripe payments easily in your application. One of the most popular is react-stripe-checkout. 

    2What is Stripe payment gateway?

    Payment gateways make it easier for you to integrate payments into your app and for users to pay through it. Stripe payment gateway is one of them. It is used by millions of companies of all kinds, from small startups to major corporations, to collect payments, send payouts, and manage their businesses online. 

    3How does Stripe.js work?

    Stripe.js is a Javascript library that helps you interact with Stripe APIs. When the user fills the details on the checkout form, Stripe.js passes the card details to the Stripe server, where it is verified and stored if it is correct. It then sends a temporary token and the personal details to your server. By using Stripe.js, your server doesn’t need to handle any card data, and hence it’s secure. 


    Ashutosh Krishna


    Ashutosh is an Application Developer at Thoughtworks. Apart from his love for Backend Development and DevOps, he has a keen interest in writing technical blogs and articles. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon