Connect to user wallets and authenticate your users using Stacks.js.
Authentication is a fundamental part of many web applications, ensuring that users are who they claim to be and that their data is secure. With the Stacks blockchain, user authentication involves connecting to users' wallets and managing their sessions securely.
The @stacks/connect package from Stacks.js provides the tools needed to integrate this functionality seamlessly into your web app.
In this guide, you will learn how to:
Install and set up the @stacks/connect package.
Initiate a userSession with specific permission scopes.
Trigger the authentication flow with the showConnect function.
Handle pending authentication states and manage user data.
Create an authenticate function that will call showConnect, triggering the popup that initiates the authentication process for users. They will authenticate with a secret key that's used to encrypt their private data.
The showConnect function accepts an object with the following properties:
The app's name and icon: provided as strings comprising the appDetails object property.
The redirectTo string: used to provide a URL to which the user should be redirected upon successful authentication.
The onFinish callback serves a similar purpose by handling successful authentication within a context of a popup window.
After initiating the authentication process, you will most likely need to handle cases where the user hasn't completed the authentication flow.
Check if there is a pending sign-in using the isSignInPending method of the userSession object.
If there is a pending sign-in, handle it by calling handlePendingSignIn which processes the sign-in and then utilizes the userData returned in a promise.
For users already signed in, you can directly access their session information and proceed with your app's flow.
Note
Implementing handlePendingSignIn is particularly important in mobile app contexts to ensure a smooth user experience across all device types.