Integrating Solana Wallet Adapter in a Next.js Application
This guide will walk you through the process of integrating the Solana Wallet Adapter in a Next.js application, enabling you to use Solana wallets seamlessly.
Table of Contents
Creating a New Next.js Project
Installing Solana Wallet Adapter Dependencies
Setting Up Solana Wallet Adapter in Your Next.js App
Adding a Connect Wallet Button
Utilizing the Wallet Context in Other Next.js Pages
Creating a New Next.js Project
First, create a new Next.js project if you don't already have one. Run the following command in your terminal:
npx create-next-app@latest my-solana-app
cd my-solana-appInstalling Solana Wallet Adapter Dependencies
Next, install the necessary Solana wallet adapter dependencies. Run the following command:
npm install @solana/wallet-adapter-react @solana/wallet-adapter-base @solana/wallet-adapter-react-ui @solana/wallet-adapter-wallets @solana/wallet-adapter-react-ui @solana/wallet-adapter-walletconnect @solana/web3.jsSetting Up Solana Wallet Adapter in Your Next.js App
Create a new file named wallet.js inside the src directory (or the appropriate directory based on your project structure). This file will set up the Solana Wallet Adapter context.
// src/wallet.js
import React, { useMemo } from 'react';
import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
import { WalletModalProvider } from '@solana/wallet-adapter-react-ui';
import { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';
import { clusterApiUrl } from '@solana/web3.js';
const WalletContextProvider = ({ children }) => {
const network = clusterApiUrl('mainnet-beta');
const wallets = useMemo(() => [new PhantomWalletAdapter()], []);
return (
<ConnectionProvider endpoint={network}>
<WalletProvider wallets={wallets} autoConnect>
<WalletModalProvider>{children}</WalletModalProvider>
</WalletProvider>
</ConnectionProvider>
);
};
export default WalletContextProvider;In pages/_app.js, wrap your application with the WalletContextProvider.
Adding a Connect Wallet Button
Create a new component for the connect wallet button, for example, components/ConnectWalletButton.js.
Use this component in any page, such as pages/index.js.
Utilizing the Wallet Context in Other Next.js Pages
You can access the wallet context using the useConnection and useWallet hooks provided by the Solana Wallet Adapter. Here’s an example of how to use these hooks in another page:
Last updated