React
Overview
The @turnkey/sdk-react
package wraps the functionality from the @turnkey/sdk-browser
package to allow developers to build react based applications that interact with the Turnkey API with different types of authentication.
It allows developers to use the same clients exposed in @turnkey/sdk-browser
that enable requests to the API to be authenticated via different auth methods like user sessions, passkey and iFrames. It also contains the same methods to manage information and state related to authentication like auth bundles and sessions, retrieving user information and server signing API requests.
Use the sdk-react package when you’re building react based frontend applications that interact with the Turnkey API.
Installation
- NPM
- Yarn
npm install @turnkey/sdk-react
yarn add @turnkey/sdk-react
Initializing
In App.tsx
(or equivalent file)
import { TurnkeyProvider } from "@turnkey/sdk-react";
const turnkeyConfig = {
apiBaseUrl: "https://api.turnkey.com",
// prefix with NEXT_PUBLIC for NextJS
defaultOrganizationId: process.env.TURNKEY_ORGANIZATION_ID,
// your application's domain
rpId: process.env.RPID,
iframeUrl: "https://auth.turnkey.com",
// The URL that the Turnkey SDK will send requests to for signing operations.
// This should be a backend endpoint that your application controls.
serverSignUrl: "http://localhost:3000/api"
}
<div className="App">
<TurnkeyProvider config={turnkeyConfig}>
// Rest of app ...
</TurnkeyProvider>
</div>
Parameters
An object containing configuration settings for the Browser Client.
defaultOrganizationId
string
required
The root organization that requests will be made from unless otherwise specified
apiBaseUrl
string
required
The base URL that API requests will be sent to (use https://api.turnkey.com when making requests to Turnkey's API)
rpId
string
The Relying Party ID used for WebAuthn flows (will default to the value returned from window.location.hostname
unless otherwise specified)
serverSignUrl
string
The URL to send requests that need to be signed from a backend codebase by the root organization's API key if using the serverSign
flow
Using The React SDK to interact with Turnkey
The @turnkey/sdk-react
package enables developers to use the functionality from the @turnkey/sdk-browser
package in react based applications.
In any React component nested under the TurnkeyProvider
, you'll be able to call useTurnkey()
and do the following:
import { useTurnkey } from "@turnkey/sdk-react";
const { turnkey, passkeyClient, authIframeClient } = useTurnkey();
const loginWithPasskey = async () => {
await passkeyClient?.login();
};
const initEmailAuth = async () => {
await turnkey?.serverSign("emailAuth", [
{
email: "<target user email>",
targetPublicKey: authIframeClient.iframePublicKey,
organizationId: "<target user suborg-id>",
},
]);
};
const loginWithIframe = async (credentialBundle: string) => {
await authIframeClient?.injectCredentialBundle(credentialBundle);
await authIframeClient?.login();
};