I'm trying to achieve what seems like a simple goal but having trouble finding a simple solution to it. Here's my problem:

Given a private key, I would like the simplest way to "inject" this key into a web app context so that all subsequent usage of the web3 object uses this as web3.eth.defaultAccount.

Before someone brings up security issues, I would like to emphasize that we can ignore security implications for now. It's a special case and I have solutions to deal with the security issue as long as this is possible.

The only solution I've found so far has been to create a custom provider and instantiate the Web3 instance with this custom provider which overrides certain methods like sendTransaction, etc.--this is how MetaMask seems to work using https://github.com/MetaMask/provider-engine.

But setting up all these custom providers just for what I'm trying to achieve--take a private key string and turn it into web3.eth.defaultAccount--feels like an overkill.

Any help would be appreciated. Thank you!

  • 1
    Did you research web3 v1.0? It has web3.eth.accounts.privateKeyToAccount (I didn't try that api yet). For web3 v0.20 I've used truffle-hdwallet-provider, it uses MetaMask's provider-engine but it easier to setup (Although you have to provide the mnemonic instead of the raw private key).
    – Ismael
    Commented Nov 6, 2017 at 21:21
  • 1
    @Ismael Yes indeed! I actually found the solution after I posted and just managed to get it to work just now. I can confirm this works. The trick is to inject it into web3.eth.wallet
    – Vlad
    Commented Nov 6, 2017 at 21:35
  • It should be good if you write what are you doing so it can help others in similar situation.
    – Ismael
    Commented Nov 6, 2017 at 21:42

1 Answer 1


Using web3js 1.0.0:

const privateKey = 'e0f34403.................................29c8c861937';
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
web3.eth.defaultAccount = account.address;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.