11---
22description : Authenticate users
3+ toc_max_heading_level : 2
34---
45
56# Authenticate users
67
7- Connect and manage user wallet sessions in your dApp. This guide covers both ** Wagmi** (recommended) and ** vanilla JavaScript** approaches.
8+ Connect and manage user wallet sessions in your [ Wagmi] ( #use-wagmi ) or
9+ [ Vanilla JavaScript] ( #use-vanilla-javascript ) dapp.
10+ With the SDK, you can:
811
912<div style ={{ display: 'flex', gap: '1rem', alignItems: 'flex-start' }} >
1013 <div style={{ flex: '3' }}>
@@ -14,23 +17,24 @@ Connect and manage user wallet sessions in your dApp. This guide covers both **W
1417 </div>
1518 <div style={{ flex: '3' }}>
1619 <ul>
17- <li><strong>Connect users' wallets</strong> to your dApp </li>
18- <li><strong>Access user accounts</strong> (addresses)</li>
19- <li><strong>Handle connection states</strong> (connected/disconnected)</li>
20- <li><strong>Listen for account changes</strong> in real- time</li>
21- <li><strong>Manage wallet sessions</strong> (connect/disconnect)</li>
22- <li><strong>Support multiple wallet types</strong> (extension, mobile app)</li>
20+ <li><strong>Connect users' wallets</strong> to your dapp. </li>
21+ <li><strong>Access user accounts</strong> (addresses). </li>
22+ <li><strong>Handle connection states</strong> (connected/disconnected). </li>
23+ <li><strong>Listen for account changes</strong> in real time. </li>
24+ <li><strong>Manage wallet sessions</strong> (connect/disconnect). </li>
25+ <li><strong>Support multiple wallet types</strong> (extension, mobile app). </li>
2326 </ul>
2427 </div>
2528</div >
2629
2730
28- ### Using Wagmi
31+ ## Use Wagmi
2932
30- Wagmi provides a simple, hook-based approach for handling wallet connections:
33+ Wagmi provides a simple, hook-based approach for handling wallet connections.
34+ For example:
3135
32- ``` tsx
33- import { useAccount , useConnect , useDisconnect } from ' wagmi'
36+ ``` tsx title="Handle wallet connections"
37+ import { useAccount , useConnect , useDisconnect } from " wagmi"
3438
3539function ConnectWallet() {
3640 const { address, isConnected } = useAccount ()
@@ -54,45 +58,44 @@ function ConnectWallet() {
5458 onClick = { () => connect ({ connector })}
5559 disabled = { isPending }
5660 >
57- { isPending ? ' Connecting...' : ` Connect ${connector .name } ` }
61+ { isPending ? " Connecting..." : ` Connect ${connector .name } ` }
5862 </button >
5963 ))}
6064 </div >
6165 )
6266}
6367```
6468
65- #### Handle Account Changes
66-
6769Wagmi provides a dedicated hook for handling account lifecycle events:
6870
6971``` tsx
70- import { useAccountEffect } from ' wagmi'
72+ import { useAccountEffect } from " wagmi"
7173
7274function WatchAccount() {
7375 useAccountEffect ({
7476 onConnect(data ) {
75- console .log (' Connected!' , {
77+ console .log (" Connected!" , {
7678 address: data .address ,
7779 chainId: data .chainId ,
7880 isReconnected: data .isReconnected
7981 })
8082 },
8183 onDisconnect() {
82- console .log (' Disconnected!' )
84+ console .log (" Disconnected!" )
8385 }
8486 })
8587
8688 return <div >Watching for account changes...</div >
8789}
8890```
8991
90- ### Using Vanilla JavaScript
92+ ## Use Vanilla JavaScript
9193
92- If you're not using React, here's how to implement authentication directly:
94+ You can implement user authentication directly in Vanilla JavaScript.
95+ For example:
9396
9497``` javascript
95- import { MetaMaskSDK } from ' @metamask/sdk' ;
98+ import { MetaMaskSDK } from " @metamask/sdk" ;
9699
97100// Initialize SDK
98101const MMSDK = new MetaMaskSDK ();
@@ -102,51 +105,45 @@ const provider = MMSDK.getProvider();
102105async function connectWallet () {
103106 try {
104107 // Disable button while request is pending
105- document .getElementById (' connectBtn' ).disabled = true ;
108+ document .getElementById (" connectBtn" ).disabled = true ;
106109
107110 const accounts = await provider .request ({
108- method: ' eth_requestAccounts'
111+ method: " eth_requestAccounts"
109112 });
110113
111114 const account = accounts[0 ];
112- console .log (' Connected:' , account);
115+ console .log (" Connected:" , account);
113116
114117 // Update UI
115- document .getElementById (' status' ).textContent = ` Connected: ${ account} ` ;
116- document .getElementById (' connectBtn' ).style .display = ' none' ;
117- document .getElementById (' disconnectBtn' ).style .display = ' block' ;
118+ document .getElementById (" status" ).textContent = ` Connected: ${ account} ` ;
119+ document .getElementById (" connectBtn" ).style .display = " none" ;
120+ document .getElementById (" disconnectBtn" ).style .display = " block" ;
118121 } catch (err) {
119122 if (err .code === 4001 ) {
120- console .log (' User rejected connection' );
123+ console .log (" User rejected connection" );
121124 } else {
122125 console .error (err);
123126 }
124127 } finally {
125- document .getElementById (' connectBtn' ).disabled = false ;
128+ document .getElementById (" connectBtn" ).disabled = false ;
126129 }
127130}
128131
129132// Handle account changes
130- provider .on (' accountsChanged' , (accounts ) => {
133+ provider .on (" accountsChanged" , (accounts ) => {
131134 if (accounts .length === 0 ) {
132135 // User disconnected
133- document .getElementById (' status' ).textContent = ' Not connected' ;
134- document .getElementById (' connectBtn' ).style .display = ' block' ;
135- document .getElementById (' disconnectBtn' ).style .display = ' none' ;
136+ document .getElementById (" status" ).textContent = " Not connected" ;
137+ document .getElementById (" connectBtn" ).style .display = " block" ;
138+ document .getElementById (" disconnectBtn" ).style .display = " none" ;
136139 } else {
137140 // Account changed
138- document .getElementById (' status' ).textContent = ` Connected: ${ accounts[0 ]} ` ;
141+ document .getElementById (" status" ).textContent = ` Connected: ${ accounts[0 ]} ` ;
139142 }
140143});
141144```
142145
143- ::: info
144-
145- Check out the [ Provider API] ( /wallet/reference/provider-api ) reference for more information.
146-
147- :::
148-
149- #### HTML
146+ Display connect and disconnect buttons in HTML:
150147
151148``` html
152149<div >
@@ -158,39 +155,54 @@ Check out the [Provider API](/wallet/reference/provider-api) reference for more
158155</div >
159156```
160157
161- ### Best Practices
158+ ::: info
159+ See the [ Provider API] ( /wallet/reference/provider-api ) reference for more information.
160+ :::
161+
162+ ## Best practices
163+
164+ Follow these best practices when authenticating users.
165+
166+ #### User interaction
167+
168+ - Only trigger connection requests in response to user actions (like selecting a button).
169+ - Never auto-connect on page load.
170+ - Provide clear feedback during connection states.
171+
172+ #### Error handling
162173
163- 1 . ** User Interaction**
164- - Only trigger connection requests in response to user actions (like button clicks)
165- - Never auto-connect on page load
166- - Provide clear feedback during connection states
174+ - Handle [ common errors] ( #common-errors ) like user rejection (code ` 4001 ` ).
175+ - Provide clear error messages to users.
176+ - Fall back gracefully when MetaMask is not installed.
167177
168- 2 . ** Error Handling**
169- - Handle common errors like user rejection (code 4001)
170- - Provide clear error messages to users
171- - Fallback gracefully when MetaMask is not installed
178+ #### Account changes
172179
173- 3 . ** Account Changes**
174- - Always listen for account changes
175- - Update your UI when accounts change
176- - Handle disconnection events
180+ - Always listen for account changes.
181+ - Update your UI when accounts change.
182+ - Handle disconnection events.
177183
178- 4 . ** Chain Support**
179- - Listen for network/chain changes
180- - Verify the current chain meets your requirements
181- - Provide clear messaging when users need to switch networks
182- - Learn more here: [ Network Management] ( /sdk/guides/network-management )
184+ #### Chain support
183185
184- ### Common Errors
186+ - Listen for network/chain changes.
187+ - Verify the current chain meets your requirements.
188+ - Provide clear messaging when users need to switch networks.
185189
186- | Error Code | Description | Solution |
190+ Learn how to [ manage networks] ( manage-networks.md ) .
191+
192+ ## Common errors
193+
194+ The following table lists common authentication errors and their codes:
195+
196+ | Error code | Description | Solution |
187197| ------------| -------------| ----------|
188- | ** 4001** | User rejected request | Show a message asking user to approve the connection |
189- | ** -32002** | Request already pending | Disable connect button while request is pending |
190- | ** -32603** | Internal JSON-RPC error | Check if MetaMask is properly installed |
198+ | ` 4001 ` | User rejected request | Show a message asking the user to approve the connection. |
199+ | ` -32002 ` | Request already pending | Disable the connect button while the request is pending. |
200+ | ` -32603 ` | Internal JSON-RPC error | Check if MetaMask is properly installed. |
201+
202+ ## Next steps
191203
192- ### Next Steps
204+ See the following guides to add more functionality to your dapp:
193205
194- - [ Network Management ] ( /sdk/guides/network-management )
195- - [ Transaction Handling ] ( /sdk/guides/transaction-handling )
196- - [ Interact with Contracts ] ( /sdk/guides/ interact-with-contracts)
206+ - [ Manage networks ] ( manage-networks.md )
207+ - [ Handle transactions ] ( handle-transactions.md )
208+ - [ Interact with smart contracts ] ( interact-with-contracts.md )
0 commit comments