Web3js Node.js – How to Get Connected Wallet Address on Server Side

nodejsserver-sideweb3js

I couldn't find a way to obtain accounts the user connected in my website in my node.js web server.

This is what I've tried

const express = require('express');
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:3000"));

const app = express();
const port = process.env.PORT || 3000;

app.set('view engine', 'ejs');

app.listen(port, () => {
    console.log("Connected!");
});

app.get('/', (request, response) => {
    // This is the page where user connects to their wallet and it works fine
    response.render('index');
});

app.get('/dashboard', async (request, response) => {
    // The user gets redirected to this page after connecting to their wallet in the index page
    console.log(web3.eth.accounts); // Returns an empty array
    response.render('dashboard');
});

I even tried to use getAccounts() and many more I can find on the internet, but it stills return empty arrays. There are literally no questions and answers about working with user's wallet address on the server side. Perhaps I am doing it wrong, or it is not possible do that on the server side. I'm not very familiar with web3 development.

Best Answer

You are correct - it's not possible to do it in the serve side. Browser wallets such as MetaMask are only available in the frontend. If you want wallet information to be available in your backend, the frontend has to forward the data to the backend.

Or if you wish to utilize blockchain in the server side, you typically have a separate connection. This is useful for example in cases where you want the backend to read blockchain data but not require users to have (or give access to their) wallet.

To utilize a separate connection from the backend (for read only access), you need access to some node - typically such as Alchemy or Infura. If you wish to also submit transactions, you'll need access to a (backend) wallet which has the necessary funds for it. This is basically just a private key stored in a secure place.

Related Topic