Using React + Vite

Using Irys With React + Vite

This guide covers how to setup an Irys project using React + Vite.

Setup a new project:

mkdir irys-vite
cd irys-vite
npm create vite@latest .
npm install

Choose React and either TypeScript or JavaScript, then:

npm install

Install the Irys SDK and ethers:

npm install @irys/sdk ethers@6

Change your App.tsx file as follows. This example uses ethers6, if you're using a different provider make sure to specify it when creating the wallet.

import "./App.css";
import { useState } from "react";
import { ethers } from "ethers";
import { WebIrys } from "@irys/sdk";
 
function App() {
	const [connectedAddress, setConnectedAddress] = useState<string>("");
 
	const getWebIrys = async () => {
		let provider;
		//@ts-ignore
		if (window.ethereum == null) {
			console.log("MetaMask not installed; using read-only defaults");
			provider = ethers.getDefaultProvider();
		} else {
			//@ts-ignore
			provider = new ethers.BrowserProvider(window.ethereum);
		}
		console.log("provider=", provider);
		const network = "mainnet";
		const token = "ethereum";
 
		const wallet = { name: "ethersv6", provider: provider };
		const webIrys = new WebIrys({ network, token, wallet });
		await webIrys.ready();
		setConnectedAddress(webIrys.address!);
	};
 
	return (
		<>
			<h1>Vite + React + Irys</h1>
			{connectedAddress && connectedAddress.length > 0 && <h3>Connected from: {connectedAddress}</h3>}
			<div className="card">
				<button onClick={getWebIrys}>Connect To Irys Node</button>
			</div>
		</>
	);
}
 
export default App;

When you load your app, you will see a blank white screen and find the following in your developer console.

Vite error
Class extends value undefined is not a constructor or null

To fix this, first install:

npm install -D crypto-browserify stream-browserify os-browserify path-browserify vite-plugin-node-polyfills vite-plugin-notifier

And then modify vite.config.ts to use the following:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { nodePolyfills } from "vite-plugin-node-polyfills";
 
// https://vitejs.dev/config/
export default defineConfig({
	resolve: {
		alias: {
			process: "process/browser",
			path: "path-browserify",
			os: "os-browserify",
			stream: "stream-browserify",
		},
	},
	plugins: [
		react(),
		nodePolyfills({
			exclude: ["fs"],
			// Whether to polyfill specific globals.
			globals: {
				Buffer: true,
				global: true,
				process: true,
			},
			// Whether to polyfill `node:` protocol imports.
			protocolImports: true,
		}),
	],
});

Restart React+Vite and you should be good to go.