Custom Truffle web3 provider to support Infura authentication

Secure Infura project key:

Nhan Cao
2 min readOct 19, 2022

Install lib:

- For Http:yarn add web3-providers-http- For Ws:yarn add web3-providers-ws

Example web3 provider configuration:

https://web3js.readthedocs.io/en/v1.7.4/web3-eth.html

// ====
// Http
// ====
const Web3HttpProvider = require('web3-providers-http');const options = {
keepAlive: true,
withCredentials: false,
timeout: 20000, // ms
headers: [
{
name: 'Access-Control-Allow-Origin',
value: '*'
},
{
...
}
],
agent: {
http: http.Agent(...),
baseUrl: ''
}
};
const provider = new Web3HttpProvider('http://localhost:8545', options);// ==========
// Websockets
// ==========
const Web3WsProvider = require('web3-providers-ws');const options = {
timeout: 30000, // ms
// Useful for credentialed urls, e.g…

--

--