Authentication
The foundation of any Stacks based application is authentication. With micro-stacks, you are able
to add authentication to any JavaScript/TypeScript application. Stacks authentication is dependent
on your users having a compatible wallet to authenticate with.
The two primary wallets in the Stacks ecosystem are: the Hiro Web Wallet and the native (iOS and Android) wallet Xverse.
Adding auth to your app
Important: before adding authentication, make sure you've properly set up your application.
The primary way you'll implement authentication is via the useAuth hook. This hook exposes a few
callbacks for different functions: openAuthRequest, signOut, along with some helper variables:
isRequestPending isSignedIn.
Check out the sample below for a very simple WalletConnectButton component:
import { useAuth } from '@micro-stacks/react';
export const WalletConnectButton = () => {
const { openAuthRequest, isRequestPending, signOut, isSignedIn } = useAuth();
const label = isRequestPending ? 'Loading...' : isSignedIn ? 'Sign out' : 'Connect Stacks wallet';
return (
<button
onClick={async () => {
if (isSignedIn) await signOut();
else await openAuthRequest();
}}
>
{label}
</button>
);
};Migrating from pre v1.0.0
The primary differences between the latest version and versions before v1.0.0 are as follows:
handleSignInrenamed toopenAuthRequesthandleSignOutrenamed tosignOutisLoadingrenamed toisRequestPendingsessionis removed from this hook, useuseAccountinstead
User account data
To access the current signed in user data, you'll want to make use of the useAccount hook:
import { useAccount } from '@micro-stacks/react';This hook will return an object with the shape:
interface Account {
appPrivateKey?: string;
stxAddress?: string;
rawAddress?: [number, Uint8Array];
identityAddress?: string;
decentralizedID?: string;
profileUrl?: string;
}Server side session
If you are building an application that uses server side rendering, or want to share state with an api route, check out these handy resources for working with Stacks apps & server rendering:
Advanced patterns: server side rendering