How to store and retrieve private key? - web3, html, javascript

Hello,

When a button is pressed, I send custom tokens to the user using the code below by signing and sending it from my account. The code works perfectly, however, how do I safely store and retrieve the “private key”? The code below is stored in a plain javascript file.

 web3.eth.accounts.signTransaction(rawTransaction, "**MY PRIVATE KEY HERE**")
      .then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
      .then(req => { 
        /* The trx was done. Write your actions here. For example, getBalance. */
        getTokenBalanceOf(userAddress).then( balance => { console.log(userAddress + " Token Balance: " + balance); });
        addCustomTokensToUsersMetaMask();
        customTokenTransferCompleted();  
        return true;  
      })  

However, how do I store this private key safely and retrieve it? I know there are ways like using .secret files, or storing it in environment variables, etc, but I can’t find a good tutorial on how to do it. I’m using regular html and javascript, I’m not using react.js. Thanks.

Never mind, I figured it out. I created a .secret file, which contains my private key, which I imported into a nodejs file. I pasted the code in my above post into the file, and the code was triggered when my smart contract event (‘Purchased’) was emitted and captured (emitted on the front end, and captured in my nodejs file). And when using events in nodejs, I had to use the below code to connect to ganache with websockets.

var web3 = new Web3("ws://127.0.0.1:7545");