Search code examples
node.jscryptographyblockchainethereumweb3js

How to sign messages on the server side using web3


I am building a decentralized app using Node.js. I need the node.js app to receive a message from the frontend, use web3.js to sign the message and send the signature back to the frontend.

I am thinking of passing as a environmental variable a predefined private key to the node.js app. Then use the private key to instantiate Web3 and call web3.personal.sign to sign the message. I need the signing process to occur on the server side, so I don't believe that using a client-side wallet like Metamask would be applicable.

I am new to Blockchain and Web3 development so I am not sure if what I am asking is feasible.


Solution

  • You can pass the private key to wallet.add(), and then sign the message using web3.eth.sign().

    web3.eth.accounts.wallet.add(SIGNER_PRIVATE_KEY);
    const message = "Hello world";
    
    // sign
    const signature = await web3.eth.sign(message, SIGNER_ADDRESS);
    
    // recover
    const recoveredSigner = web3.eth.accounts.recover(message, signature);
    console.log(recoveredSigner == SIGNER_ADDRESS);