0.6.0 • Published 11 months ago

@farcaster/auth-kit v0.6.0

Weekly downloads
-
License
MIT
Repository
-
Last release
11 months ago

@farcaster/auth-kit

A React library that makes it easy to add Sign In With Farcaster to your application.

Getting Started

Installation

Install AuthKit and its peer dependency viem.

npm install @farcaster/auth-kit viem

Note: AuthKit is a React library. If you're using another frontend framework, take a look at the @farcaster/auth-client library instead.

Import

Import styles and functions.

import "@farcaster/auth-kit/styles.css";
import { AuthKitProvider } from "@farcaster/auth-kit";

Add Provider

Wrap your application with AuthKitProvider.

const config = {
  // For a production app, replace this with an Optimism Mainnet
  // RPC URL from a provider like Alchemy or Infura.
  rpcUrl: "https://mainnet.optimism.io",
  domain: "example.com",
  siweUri: "https://example.com/login",
};

const App = () => {
  return <AuthKitProvider config={config}>{/* Your App */}</AuthKitProvider>;
};

Add the sign in button

Then, in your app, import and render the SignInButton component.

import { SignInButton } from "@farcaster/auth-kit";

export const SignIn = ({ nonce }: { nonce: string }) => {
  return <SignInButton nonce={nonce} />;
};

A Sign in with Farcaster button will be rendered. When the user clicks it they will be prompted to complete sign in using their Farcaster wallet application. Once they complete sign in a signed message will be returned to your callback.

Examples

You can find official examples here.

Troubleshooting

Projects using Create React App (CRA) may run into TypeScript version conflicts, as react-scripts@5.0.1 expects a peer dependency of TypeScript version ^3.2.1 || ^4, while both viem and AuthKit require >=5.0.4.

To resolve this issue:

  • Install the latest version of TypeScript: npm i typescript -D
  • Add an override for react-scripts to your package.json file, to remove the version ceiling:
"overrides": {
  "react-scripts": {
    "typescript": ">3.2.1"
  }
}

Note: Always be careful with overrides and ensure they are compatible with the packages using them.

Components

AuthKitProvider

Wrap your application in an AuthKitProvider to use Farcaster Auth.

const config = {
  domain: "example.com",
  siweUri: "https://example.com/login",
  rpcUrl: "https://mainnet.optimism.io",
  relay: "https://relay.farcaster.xyz",
};

const App = () => {
  return <AuthKitProvider config={config}>{/* Your App */}</AuthKitProvider>;
};

Props

PropTypeRequiredDescription
configAuthKitConfigYesConfiguration object. See options in the table below.

config options:

ParameterTypeRequiredDescriptionDefault
domainstringYesDomain of your application.None
siweUristringYesA URI identifying your application.None
relaystringNoFarcaster Auth relay server URLhttps://relay.farcaster.xyz
rpcUrlstringNoOptimism RPC server URLhttps://mainnet.optimism.io
versionstringNoFarcaster Auth versionv1

SignInButton

The main component. Renders a "Sign in With Farcaster" button that prompts the user to scan a QR code with their phone on web or redirects directly on a mobile device. You can use a callback prop or a hook to access the user's authentication status and profile information.

import { SignInButton } from "@farcaster/auth-kit";

export const SignIn = ({ nonce }: { nonce: string }) => {
  return (
    <SignInButton
      nonce={nonce}
      onSuccess={({ fid, username }) =>
        console.log(`Hello, ${username}! Your fid is ${fid}.`)
      }
    />
  );
};

Props

PropTypeRequiredDescriptionDefault
timeoutnumberNoRelay server timeout in ms.300000 (5 minutes)
intervalnumberNoRelay server polling interval in ms.1500 (1.5 seconds)
noncestringNoRandom nonce to include in the Sign In With Farcaster message.None
notBeforestringNoTime when the SIWF message becomes valid. ISO 8601 datetime string.None
expirationTimestringNoTime when the SIWF message expires. ISO 8601 datetime string.None
requestIdstringNoAn optional system specific ID to include in the SIWF message.None
onSuccess(res: UseSignInData) => voidNoCallback invoked when sign in is complete and the user is authenticated.None
onStatusResponse(res: UseWatchStatusData) => voidNoCallback invoked when the component receives a status update from the relay server.None
onError(error: AuthClientError) => voidNoError callback function.None
debugbooleanNoRender a debug panel displaying internal AuthKit state.false

Hooks

useSignIn

Hook for signing in a user. Connects to the relay server, generates a QR code and sign in link to present to the user, and polls relay server for wallet signature.

import { QRCode, useSignIn } from "@farcaster/auth-kit";

function App() {
  const {
    signIn,
    url
    data: { username },
    onSuccess: ({ fid }) => console.log("Your fid:", fid);
  } = useSignIn();

  return (
    <div>
      <button onClick={signIn}>Sign In</button>
      {qrCodeUri && (
        <span>
          Scan this: <QRCode uri={url} />
        </span>
      )}
      {username && `Hello, ${username}!`}
    </div>
  );
}

Parameters

ParameterTypeRequiredDescriptionDefault
timeoutnumberNoRelay server timeout in ms.300000 (5 minutes)
intervalnumberNoRelay server polling interval in ms.1500 (1.5 seconds)
noncestringNoRandom nonce to include in the Sign In With Farcaster message.None
notBeforestringNoTime when the SIWF message becomes valid. ISO 8601 datetime string.None
expirationTimestringNoTime when the SIWF message expires. ISO 8601 datetime string.None
requestIdstringNoAn optional system specific ID to include in the SIWF message.None
onSuccess(res: UseSignInData) => voidNoCallback invoked when sign in is complete and the user is authenticated.None
onStatusResponse(res: UseWatchStatusData) => voidNoCallback invoked when the component receives a status update from the relay server.None
onError(error: AuthClientError) => voidNoError callback function.None

Returns

  {
    signIn: () => void;
    reconnect: () => void;
    isSuccess: boolean;
    isPolling: boolean;
    isError: boolean;
    error: AuthClientError;
    channelToken: string;
    url: string;
    qrCodeUri: string;
    data: {
        state: "pending" | "complete";
        nonce: string;
        message: string;
        signature: string;
        fid: number;
        username: string;
        bio: string;
        displayName: string;
        pfpUrl: string;
        custody: Hex;
        verifications: Hex[];
    },
    validSignature: boolean;
  };
ParameterDescription
signInCall this function to connect to the relay and poll for a signature.
reconnectReconnect to the relay and try again. Use in the event of an error.
isSuccessTrue when the relay server returns a valid signature.
isPollingTrue when the relay state is "pending" and the app is polling the relay server for a response.
isErrorTrue when an error has occurred.
errorAuthClientError instance.
channelTokenFarcaster Auth relay channel token.
urlSign in With Farcaster URL to present to the user. Links to Warpcast in v1.
qrcodeUriQR code image data URI encoding url.
data.stateStatus of the sign in request, either "pending" or "complete"
data.nonceRandom nonce used in the SIWE message. If you do not provide a custom nonce, read this value.
data.messageThe generated SIWE message.
data.signatureHex signature produced by the user's Warpcast wallet.
data.fidUser's Farcaster ID.
data.usernameUser's Farcaster username.
data.bioUser's Farcaster bio.
data.displayNameUser's Farcaster display name.
data.pfpUrlUser's Farcaster profile picture URL.
data.custodyUser's Farcaster ID custody address.
data.verificationsUser's verified addresses.
validSignatureTrue when the signature returned by the relay server is valid.

useProfile

Hook for reading information about the authenticated user.

import { useProfile } from "@farcaster/auth-kit";

function App() {
  const {
    isAuthenticated,
    profile: { fid, pfpUrl, username, displayName, bio },
  } = useProfile();

  return (
    <div>
     { isAuthenticated ? <p>Hello, {username}! Your fid is {fid}.<p>  : <p>You're not signed in.</p>}
    </div>
  );
}

Returns

  {
    isAuthenticated: boolean;
    profile: {
        fid: number;
        username: string;
        bio: string;
        displayName: string;
        pfpUrl: string;
    },
  };
ParameterDescription
isAuthenticatedTrue if the user is authenticated.
profile.fidUser's Farcaster ID.
profile.usernameUser's Farcaster username.
profile.bioUser's Farcaster bio.
profile.displayNameUser's Farcaster display name.
profile.pfpUrlUser's Farcaster profile picture URL.
profile.custodyUser's Farcaster ID custody address.
profile.verificationsUser's verified addresses.

useSignInMessage

Hook for reading the SIWE message and signature used to authenticate the user.

import { useSignInMessage } from "@farcaster/auth-kit";

function App() {
  const { message, signature } = useSignInMessage();

  return (
    <div>
      <p>You signed: {message}</p>
      <p>Your signature: {signature}</p>
    </div>
  );
}

Returns

{
  message: string;
  signature: string;
}
ParameterDescription
messageSIWE message signed by the user.
signatureSignature produced by the user's Warpcast wallet.
0.5.0

11 months ago

0.4.0

11 months ago

0.3.1

1 year ago

0.6.0

11 months ago

0.3.0

1 year ago

0.2.2

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.1.0

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.1.4

1 year ago

0.1.3

1 year ago

0.0.38

2 years ago

0.0.39

2 years ago

0.0.36

2 years ago

0.0.37

2 years ago

0.0.35

2 years ago

0.0.34

2 years ago

0.0.33

2 years ago

0.0.32

2 years ago