### Get Current User Example
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/users/get-user
Example of how to fetch the currently authenticated user's information using the Stytch React SDK.
```APIDOC
## Get Current User Example
### Description
This example demonstrates how to use the `useStytch` hook and the `stytch.user.get()` method to retrieve the current user's data within a React component.
### Method
`stytch.user.get()`
### Request Example
```jsx
import { useEffect, useState } from 'react';
import { useStytch } from '@stytch/react';
export const Home = () => {
const stytch = useStytch();
const [user, setUser] = useState(null);
useEffect(() => {
const fetchUser = async () => {
const currentUser = await stytch.user.get();
setUser(currentUser);
};
fetchUser();
}, [stytch]);
return user ?
Welcome, {user.name.first_name}
:
Log in to continue!
;
};
```
### Response Example (Success Response - 200)
```json
{
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"emails": [
{
"email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953",
"email": "sandbox@stytch.com",
"verified": true
}
],
"phone_numbers": [],
"status_code": 200
}
```
```
--------------------------------
### Install Stytch React SDK using npm
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/installation
Installs the necessary Stytch React package using npm. This is the first step in integrating Stytch into your React application.
```bash
npm install @stytch/react
```
--------------------------------
### Stytch Passkey Registration Event Data Example (JavaScript)
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/prebuilt-ui/stytch-passkey-registration
An example of the data structure received by the `PASSKEY_REGISTER` event callback. This data includes user and session information along with the WebAuthn registration ID.
```javascript
{
user_id: "user_id",
session: { ... },
user: { ... },
webauthn_registration_id: "webauthn-registration-test-db72fcc0-edae-4bb4-8d52-0b2a765683df"
}
```
--------------------------------
### Password Reset Initiation
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/passwords/reset-by-email-start
This section demonstrates how to call the `resetByEmailStart` method to initiate a password reset for a given email address. It includes a React component example and response examples for various status codes.
```APIDOC
## POST /passwords/reset/start
### Description
Initiates the password reset flow for a user by sending a magic link to their email address.
### Method
POST
### Endpoint
`/passwords/reset/start`
### Parameters
#### Request Body
- **email** (string) - Required - The email address of the user for whom to reset the password.
### Request Example
```jsx
import { useCallback } from 'react';
import { useStytch } from '@stytch/react';
export const Login = () => {
const stytch = useStytch();
const resetPasswordStart = useCallback(() => {
stytch.passwords.resetByEmailStart({
email: '${exampleEmail}',
});
}, [stytch]);
return ;
};
```
### Response
#### Success Response (200)
- **user_id** (string) - The unique ID of the affected User.
- **email_id** (string) - The unique ID of a specific email address.
- **request_id** (string) - Globally unique UUID that is returned with every API call. This value is important to log for debugging purposes; we may ask for this value to help identify a specific API call when helping you debug an issue.
- **status_code** (number) - The HTTP status code of the response. Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, 3XX values are redirects, 4XX are client errors, and 5XX are server errors.
#### Response Example
```json
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"email_id": "email-test-81bf03a8-86e1-4d95-bd44-bb3495224953"
}
```
#### Error Responses
- **404 Not Found**
- **error_type** (string) - `email_not_found`
- **error_message** (string) - Email could not be found.
- **error_url** (string) - URL for more information on the error.
```json
{
"status_code": 404,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "email_not_found",
"error_message": "Email could not be found.",
"error_url": "https://stytch.com/docs/api/errors/404"
}
```
- **429 Too Many Requests**
- **error_type** (string) - `too_many_requests`
- **error_message** (string) - Too many requests have been made.
- **error_url** (string) - URL for more information on the error.
```json
{
"status_code": 429,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "too_many_requests",
"error_message": "Too many requests have been made.",
"error_url": "https://stytch.com/docs/api/errors/429"
}
```
- **500 Internal Server Error**
- **error_type** (string) - `internal_server_error`
- **error_message** (string) - Oops, something seems to have gone wrong, please reach out to support@stytch.com to let us know what went wrong.
- **error_url** (string) - URL for more information on the error.
```json
{
"status_code": 500,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "internal_server_error",
"error_message": "Oops, something seems to have gone wrong, please reach out to support@stytch.com to let us know what went wrong.",
"error_url": "https://stytch.com/docs/api/errors/500"
}
```
```
--------------------------------
### useStytchUser Hook Example
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/hooks/use-stytch-user
Example usage of the `useStytchUser` hook in React to display a welcome message based on user authentication status.
```APIDOC
## useStytchUser Hook Example
### Description
Example usage of the `useStytchUser` hook in React to display a welcome message based on user authentication status.
### Request Example
```jsx React theme={null}
import { useStytchUser } from '@stytch/react';
export const Home = () => {
const { user } = useStytchUser();
return user ?
Welcome, {user.name.first_name}
:
Log in to continue!
;
};
```
### Response Example
```json Logged in theme={null}
{
// User object details here
}
```
```
--------------------------------
### Start Google OAuth Flow with Stytch React SDK
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/oauth/start
This code snippet demonstrates how to initiate the Google OAuth flow using the Stytch React SDK. It configures the login and signup redirect URLs, specifies custom scopes for Google Drive and Documents, and includes a `login_hint` parameter for a pre-populated email address. This function is intended to be called on a button click to start the authentication process.
```jsx
import { useStytch } from '@stytch/react';
export const Login = () => {
const stytch = useStytch();
const startOAuth = () =>
stytch.oauth.google.start({
login_redirect_url: '${exampleURL}/authenticate',
signup_redirect_url: '${exampleURL}/authenticate',
custom_scopes: [
'https://www.googleapis.com/auth/documents.readonly',
'https://www.googleapis.com/auth/drive.readonly',
],
provider_params: {
login_hint: 'example_hint@stytch.com',
},
});
return ;
};
```
--------------------------------
### Authenticate by URL
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/impersonation/authenticate
This example demonstrates how to use the `authenticateByUrl` method from the Stytch React SDK to handle authentication redirects.
```APIDOC
## POST /v1/sessions/authenticate
### Description
Handles authentication callbacks by verifying session tokens or JWTs received via URL parameters after a user has authenticated through a third-party provider or other Stytch flows.
### Method
POST
### Endpoint
/v1/sessions/authenticate
### Parameters
#### Query Parameters
- **token** (string) - Required - The token received from the authentication flow (e.g., email magic link, OAuth, etc.).
### Request Body
None
### Request Example
```jsx
import { useEffect } from 'react';
import { useStytch } from '@stytch/react';
export const Authenticate = () => {
const stytch = useStytch();
useEffect(() => {
stytch.authenticateByUrl();
}, [stytch]);
return
Loading
;
};
```
### Response
#### Success Response (200)
- **status_code** (integer) - The HTTP status code of the response. 200 indicates success.
- **request_id** (string) - A unique identifier for the request.
- **user_id** (string) - The unique identifier for the authenticated user.
- **user** (object) - An object containing user details.
- **session_token** (string) - A token representing the user's session.
- **session_jwt** (string) - A JSON Web Token representing the user's session.
- **session** (object) - An object containing session details.
#### Response Example (200)
```json
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"user": {...},
"session_token": "mZAYn5aLEqKUlZ_Ad9U_fWr38GaAQ1oFAhT8ds245v7Q",
"session_jwt": "eyJ...",
"session": {...}
}
```
#### Error Response (429)
- **status_code** (integer) - The HTTP status code of the response. 429 indicates too many requests.
- **request_id** (string) - A unique identifier for the request.
- **error_type** (string) - A machine-readable error type.
- **error_message** (string) - A human-readable error message.
- **error_url** (string) - A URL to documentation about the error.
#### Response Example (429)
```json
{
"status_code": 429,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "too_many_requests",
"error_message": "Too many requests have been made.",
"error_url": "https://stytch.com/docs/api/errors/429"
}
```
#### Error Response (500)
- **status_code** (integer) - The HTTP status code of the response. 500 indicates an internal server error.
- **request_id** (string) - A unique identifier for the request.
- **error_type** (string) - A machine-readable error type.
- **error_message** (string) - A human-readable error message.
- **error_url** (string) - A URL to documentation about the error.
#### Response Example (500)
```json
{
"status_code": 500,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "internal_server_error",
"error_message": "Oops, something seems to have gone wrong, please reach out to support@stytch.com to let us know what went wrong.",
"error_url": "https://stytch.com/docs/api/errors/500"
}
```
```
--------------------------------
### OAuth Start Flow
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/oauth/start
Initiates an OAuth authentication flow for a specified provider. This method redirects the user to the OAuth provider's authorization page and handles PKCE code generation and storage.
```APIDOC
## POST /oauth/$provider/start
### Description
Starts an OAuth authentication flow by redirecting the browser to a Stytch OAuth start endpoint. This method also generates and stores a PKCE `code_verifier`.
### Method
POST
### Endpoint
/oauth/$provider/start
### Parameters
#### Path Parameters
- **provider** (string) - Required - The OAuth provider (e.g., google, facebook, github).
#### Query Parameters
None
#### Request Body
- **configuration** (object) - Optional - Additional configuration for the OAuth flow.
- **login_redirect_url** (string) - Optional - The URL Stytch redirects to after the OAuth flow for an existing user. Must be configured as a Login URL in the Stytch dashboard.
- **signup_redirect_url** (string) - Optional - The URL Stytch redirects to after the OAuth flow for a new user. Must be configured as a Signup URL in the Stytch dashboard.
- **custom_scopes** (string) - Optional - A space-separated list of custom scopes to include, URL-encoded.
- **provider_params** (object) - Optional - An object containing parameters to pass to the OAuth provider (e.g., `login_hint`). Consult provider documentation for supported parameters.
- **oauth_attach_token** (string) - Optional - A single-use token for attaching an OAuth request to a user selection.
### Request Example
```jsx
import { useStytch } from '@stytch/react';
export const Login = () => {
const stytch = useStytch();
const startOAuth = () =>
stytch.oauth.google.start({
login_redirect_url: 'https://example.com/authenticate',
signup_redirect_url: 'https://example.com/authenticate',
custom_scopes: [
'https://www.googleapis.com/auth/documents.readonly',
'https://www.googleapis.com/auth/drive.readonly',
],
provider_params: {
login_hint: 'example_hint@stytch.com',
},
});
return ;
};
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the OAuth flow was started successfully.
#### Error Response
- **success** (boolean) - Indicates if the OAuth flow was started successfully (will be false).
- **error** (object) - The error object.
- **reason** (string) - The reason for the error. Possible values: `User Canceled`, `Authentication Failed`, `Invalid Platform`.
#### Response Example
```json
{
"success": true
}
```
#### Error Response Example
```json
{
"success": false,
"error": {},
"reason": "Authentication Failed"
}
```
```
--------------------------------
### Stytch WebAuthn Registration Response Examples
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/webauthn/register
These JSON examples illustrate the expected response structure from the Stytch API for WebAuthn registration, covering successful registration (200) and various error conditions (400, 404, 429, 500). Each response includes a status code, request ID, and relevant error details when applicable.
```json
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"webauthn_registration_id": "webauthn-registration-test-5c44cc6a-8af7-48d6-8da7-ea821342f5a6"
}
```
```json
{
"status_code": 400,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "invalid_public_key_credential",
"error_message": "Invalid public key credential. Please confirm you're passing a correctly formatted public key credential.",
"error_url": "https://stytch.com/docs/api/errors/400"
}
```
```json
{
"status_code": 404,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "user_not_found",
"error_message": "User could not be found.",
"error_url": "https://stytch.com/docs/api/errors/404"
}
```
```json
{
"status_code": 429,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "too_many_requests",
"error_message": "Too many requests have been made.",
"error_url": "https://stytch.com/docs/api/errors/429"
}
```
```json
{
"status_code": 500,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "internal_server_error",
"error_message": "Oops, something seems to have gone wrong, please reach out to support@stytch.com to let us know what went wrong.",
"error_url": "https://stytch.com/docs/api/errors/500"
}
```
--------------------------------
### Stytch Passkey Registration Component Usage (React)
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/prebuilt-ui/stytch-passkey-registration
Example of how to use the StytchPasskeyRegistration component in a React application. It demonstrates passing a configuration object with passkey options.
```jsx
import { Products, StytchPasskeyRegistration } from '@stytch/react';
const config = {
passkeysOptions: {
domain: 'example.com',
},
};
export const PasskeyRegistration = () => {
return ;
};
```
--------------------------------
### POST /oauth/authorize/start
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/connected-apps/start-oauth-authorization
The `oauthAuthorizeStart` method initiates the OAuth 2.0 authorization flow. It redirects the user to the identity provider's authorization server to grant permissions to your connected application. You need to provide your connected app's client ID, a redirect URI, the desired response type, and the scopes you wish to request.
```APIDOC
## POST /oauth/authorize/start
### Description
Initiates the OAuth 2.0 authorization flow by redirecting the user to the identity provider's authorization server. The user will be prompted to grant permissions to your connected application for the requested scopes.
### Method
POST
### Endpoint
/oauth/authorize/start
### Parameters
#### Query Parameters
- **client_id** (string) - Required - The client ID of your connected application.
- **redirect_uri** (string) - Required - The URI to redirect the user to after authorization.
- **response_type** (string) - Required - The type of response requested. Typically 'code' for authorization code flow.
- **scopes** (array[string]) - Required - A list of scopes to request from the user.
- **prompt** (string) - Optional - Specifies whether the user should be re-prompted for consent. Supported values: 'consent'.
### Request Example
```jsx
import { useStytch } from '@stytch/react';
const stytch = useStytch();
stytch.idp.oauthAuthorizeStart({
client_id: 'YOUR_CLIENT_ID',
redirect_uri: 'https://your.app.com/callback',
response_type: 'code',
scopes: ['openid', 'profile', 'email'],
prompt: 'consent',
});
```
### Response
#### Success Response (200)
This method typically results in a redirect, not a direct JSON response. The redirect will initiate the OAuth flow.
#### Response Example
(This endpoint initiates a redirect, so a direct JSON response is not applicable. The subsequent callback to your `redirect_uri` will contain authorization details.)
```
--------------------------------
### Exchange Access Token with Stytch React SDK
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/sessions/exchange-access-token
This snippet shows how to use the `useStytch` hook to get the Stytch client and then call the `exchangeAccessToken` method. It requires an access token and a session duration. The function is wrapped in `useCallback` for performance optimization. This example assumes you have a Stytch token available as '${token}'.
```jsx
import { useCallback } from 'react';
import { useStytch } from '@stytch/react';
export const App = () => {
const stytch = useStytch();
const exchangeAccessToken = useCallback(() => {
stytch.session.exchangeAccessToken({
access_token: '${token}',
session_duration_minutes: 60,
});
}, [stytch]);
return ;
};
```
--------------------------------
### POST /crypto-wallets/authenticate-start
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/crypto-wallets/authenticate-start
Initiates the crypto wallet authentication process by prompting the user to sign a challenge. Supports Ethereum (including EVM-compatible chains) and Solana wallets. Can be configured for the Sign In With Ethereum (SIWE) protocol.
```APIDOC
## POST /crypto-wallets/authenticate-start
### Description
Initiates the crypto wallet authentication process by prompting the user to sign a challenge. Supports Ethereum (including EVM-compatible chains) and Solana wallets. Can be configured for the Sign In With Ethereum (SIWE) protocol.
### Method
POST
### Endpoint
/crypto-wallets/authenticate-start
### Parameters
#### Request Body
- **crypto_wallet_type** (string) - Required - The type of wallet to authenticate. Currently ethereum and solana are supported. Wallets for any EVM-compatible chains (such as Polygon or BSC) are also supported and are grouped under the ethereum type.
- **crypto_wallet_address** (string) - Required - The crypto wallet address to authenticate.
- **siwe_params** (object) - Optional - The parameters for a Sign In With Ethereum (SIWE) message. May only be passed if the crypto_wallet_type is ethereum and if SIWE is enabled in the Stytch dashboard.
- **uri** (string) - Optional - Defaults to window.location.origin. An RFC 3986 URI referring to the resource that is the subject of the signing.
- **statement** (string) - Optional - A human-readable ASCII assertion that the user will sign. The statement may only include reserved, unreserved, or space characters according to RFC 3986 definitions, and must not contain other forms of whitespace such as newlines, tabs, and carriage returns.
- **chain_id** (string) - Optional - The EIP-155 Chain ID to which the session is bound. Defaults to 1. Must be the string representation of an integer between 1 and 9,223,372,036,854,775,771, inclusive.
- **issued_at** (string) - Optional - The time when the message was generated. Defaults to the current time. All timestamps in our API conform to the RFC 3339 standard and are expressed in UTC, e.g. 2021-12-29T12:33:09Z.
- **not_before** (string) - Optional - The time when the signed authentication message will become valid. Defaults to the current time. All timestamps in our API conform to the RFC 3339 standard and are expressed in UTC, e.g. 2021-12-29T12:33:09Z.
- **message_request_id** (string) - Optional - A system-specific identifier that may be used to uniquely refer to the sign-in request. The message_request_id must be a valid pchar according to RFC 3986 definitions.
- **resources** (array[string]) - Optional - A list of information or references to information the user wishes to have resolved as part of authentication. Every resource must be an RFC 3986 URI.
### Request Example
```json
{
"crypto_wallet_type": "ethereum",
"crypto_wallet_address": "0x1234567890abcdef1234567890abcdef12345678",
"siwe_params": {
"uri": "https://example.com",
"statement": "Please sign this message to verify your identity.",
"chain_id": "1",
"issued_at": "2021-12-29T12:33:09Z",
"not_before": "2021-12-29T12:33:09Z",
"message_request_id": "req_abc123",
"resources": ["https://example.com/resource1"]
}
}
```
### Response
#### Success Response (200)
- **challenge** (string) - The challenge data to be signed by the user's crypto wallet.
- **session_token** (string) - The session token if authentication is successful.
- **session_jwt** (string) - The session JWT if authentication is successful.
#### Response Example
```json
{
"challenge": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
"session_token": "stytch_session_token_example",
"session_jwt": "stytch_session_jwt_example"
}
```
```
--------------------------------
### Initialize Stytch Client in React
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/installation
Initializes the Stytch client by passing your Project's public token. This client is essential for all Stytch functionalities. It supports environment variables for token management.
```jsx
import { StytchClient } from '@stytch/react';
const stytch = new StytchClient(
import.meta.env.STYTCH_PUBLIC_TOKEN, // or process.env.STYTCH_PUBLIC_TOKEN for non-Vite based projects
);
```
--------------------------------
### Get Recovery Codes
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/totps/get-recovery-codes
Retrieves the recovery codes for a TOTP instance associated with a user. This method may require MFA if other methods are enrolled.
```APIDOC
## GET /totp/recovery-codes
### Description
Fetches the recovery codes for a user's TOTP instance. This operation might trigger an MFA challenge if the user has other MFA methods enrolled.
### Method
GET
### Endpoint
/totp/recovery-codes
### Parameters
#### Query Parameters
None
#### Request Body
None
### Request Example
```jsx
import { useCallback } from 'react';
import { useStytch } from '@stytch/react';
export const Login = () => {
const stytch = useStytch();
const trigger = useCallback(() => {
stytch.totps.recoveryCodes();
}, [stytch]);
return ;
};
```
### Response
#### Success Response (200)
- **user_id** (string) - The unique ID of the affected User.
- **totps** (array[objects]) - An array containing a list of all TOTP instances for a given User.
- **totp_id** (string) - The unique ID for a TOTP instance.
- **verified** (boolean) - Indicates if the associated method (e.g., phone number, email) has been successfully authenticated by the User.
- **recovery_codes** (array[strings]) - The recovery codes used to authenticate the user without an authenticator app.
- **request_id** (string) - Globally unique UUID for the API call, useful for debugging.
- **status_code** (number) - The HTTP status code of the response.
#### Response Example (200)
```json
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"user_id": "user-test-16d9ba61-97a1-4ba4-9720-b03761dc50c6",
"totps": [
{
"totp_id": "totp-test-41920359-8bbb-4fe8-8fa3-aaa83f35f02c",
"verified": true,
"recovery_codes": [
"ckss-2skx-ebow",
"spbc-424h-usy0",
"hi08-n5tk-lns5",
"1n6i-l5na-8axe",
"aduj-eufq-w6yy",
"i4l3-dxyt-urmx",
"ayyi-utb0-gj0s",
"lz0m-02bi-psbx",
"l2qm-zrk1-8ujs",
"c2qd-k7m4-ifmc"
]
}
]
}
```
#### Error Responses
- **400 Bad Request**: Returned for invalid input, such as an invalid public key credential.
- **error_type**: "invalid_public_key_credential"
- **error_message**: "Invalid public key credential. Please confirm you're passing a correctly formatted public key credential."
- **error_url**: "https://stytch.com/docs/api/errors/400"
- **404 Not Found**: Returned if the user is not found.
- **error_type**: "user_not_found"
- **error_message**: "User could not be found."
- **error_url**: "https://stytch.com/docs/api/errors/404"
- **429 Too Many Requests**: Returned if the rate limit has been exceeded.
- **error_type**: "too_many_requests"
- **error_message**: "Too many requests have been made."
- **error_url**: "https://stytch.com/docs/api/errors/429"
- **500 Internal Server Error**: Returned for unexpected server errors.
- **error_type**: "internal_server_error"
- **error_message**: "Oops, something seems to have gone wrong, please reach out to support@stytch.com to let us know what went wrong."
- **error_url**: "https://stytch.com/docs/api/errors/500"
#### Error Response Example (400)
```json
{
"status_code": 400,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"error_type": "invalid_public_key_credential",
"error_message": "Invalid public key credential. Please confirm you're passing a correctly formatted public key credential.",
"error_url": "https://stytch.com/docs/api/errors/400"
}
```
```
--------------------------------
### Prebuilt UI Configuration
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/prebuilt-ui/login/configuration
This section outlines the various configuration options available for customizing the Stytch React SDK's prebuilt UI, including session management, theming, presentation options, icons, callbacks, and custom strings.
```APIDOC
## Configuration Options for Stytch React SDK Prebuilt UI
### Description
This documentation details the parameters used to configure the Stytch React SDK's prebuilt UI, allowing for extensive customization of user experience, appearance, and behavior.
### Method
N/A (Configuration object for SDK initialization)
### Endpoint
N/A
### Parameters
#### Request Body (Configuration Object)
- **domain** (string) - Optional - Sets the domain option for both WebAuthn registration and authentication. Defaults to the current page's hostname.
- **sessionOptions** (object) - Optional - The options for session management.
- **sessionDurationMinutes** (number) - Optional - Set the session lifetime to be this many minutes from now; minimum of 5 and a maximum of 527040 minutes (366 days). Note that a successful authentication will continue to extend the session this many minutes.
- **presentation** (object) - Optional - Allows customization of the SDK's look and feel.
- **presentation.theme** (object or array) - Optional - The `presentation.theme` object allows you to customize the look of the SDK. You can specify some of them or none at all. We'll use our defaults for the ones you don't specify. If you pass in an array of two themes, the first will automatically be used when the user's OS is in light mode, and the second in dark mode. See [our pre-built themes](../theming#pre-built-themes), [how to write your own theme](../theming#creating-your-own-theme) or [reference for all properties](../theming#reference).
- **presentation.options** (object) - Optional - The `presentation.options` object customizes non-style related aspects of the SDK's appearance.
- **presentation.options.hideHeaderText** (boolean) - Optional - When this value is true, the title and description text will not show in the SDK.
- **presentation.options.logo** (object) - Optional - The configuration object for your custom logo.
- **presentation.options.logo.url** (string) - Required - The URL of your custom logo.
- **presentation.options.logo.alt** (string) - Required - The alt text for the logo for non-visual users. This is required for accessibility.
- **presentation.icons** (object) - Optional - Allows our icons to be overridden. See [icon customization guide](../theming#icon-customization) for more information.
- **callbacks** (object) - Optional - Optional callbacks that are triggered by various events in the SDK. See more details about the callbacks [here](/api-reference/consumer/frontend-sdks/react/prebuilt-ui/login/callbacks).
- **callbacks.onEvent** ((data) => void) - Optional - A callback function that responds to events sent from the SDK.
- **callbacks.onError** ((data) => void) - Optional - A callback function that responds to errors in the SDK. It is useful for debugging during development and error handling in production.
- **strings** (object) - Optional - Specify custom strings to be used in the prebuilt UI. Consult the message catalog (messages/en.po) for the list of available strings. Each value should be specified using ICU MessageFormat. Strings that are not defined will use the default English value as a fallback. See [Text Customization](/api-reference/consumer/frontend-sdks/react/prebuilt-ui/text-customization) for more information.
### Request Example
```jsx
const config = {
products: [Products.emailMagicLinks, Products.oauth],
oauthOptions: {
providers: [
{ type: 'google', one_tap: true },
{ type: 'microsoft' }
],
loginRedirectURL: 'https://example.com/authenticate',
signupRedirectURL: 'https://example.com/authenticate',
},
emailMagicLinksOptions: {
loginRedirectURL: 'https://example.com/authenticate',
signupRedirectURL: 'https://example.com/authenticate',
},
sessionOptions: {
sessionDurationMinutes: 60,
},
};
const presentation = {
theme: { 'font-family': 'Arial' },
options: { hideHeaderText: false },
};
const callbacks = {
onEvent: ({ type, data }) => {
console.log(type, data);
},
onError: (error) => {
console.log(error);
},
};
const strings = {
'login.title': 'Log in or sign up',
};
// Usage within your React component:
//
```
### Response
N/A (This is a client-side configuration)
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### User Get Connected Apps
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/connected-apps/get-connected-apps
Retrieves a list of Connected Apps that the user has completed an authorization flow with successfully. The `user_id` is automatically inferred from the logged-in user's session.
```APIDOC
## GET /v1/connected_apps
### Description
Retrieves a list of Connected Apps that the user has completed an authorization flow with successfully. If the user revokes a Connected App's access, it will no longer be returned in this endpoint's response.
### Method
GET
### Endpoint
/v1/connected_apps
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
- **connected_apps** (array[objects]) - An array of Connected Apps with which the User has successfully completed an authorization flow.
- **connected_app_id** (string) - The ID of the Connected App.
- **name** (string) - The name of the Connected App.
- **description** (string) - A description of the Connected App.
- **client_type** (string) - The type of Connected App. Supported values are first_party, first_party_public, third_party, and third_party_public.
- **logo_url** (string) - The logo URL of the Connected App, if any.
- **scopes_granted** (string) - The scopes granted to the Connected App at the completion of the last authorization flow.
- **request_id** (string) - Globally unique UUID that is returned with every API call.
- **status_code** (number) - The HTTP status code of the response.
#### Response Example
```json
{
"status_code": 200,
"request_id": "request-id-test-b05c992f-ebdc-489d-a754-c7e70ba13141",
"connected_apps": [
{
"client_type": "first_party",
"connected_app_id": "connected-app-test-aeadeabc-a3a3-4796-83d0-b757e3001000",
"description": "A first party connected app",
"logo_url": null,
"name": "first-party-confidential-app",
"scopes_granted": "openid profile email"
}
]
}
```
#### Error Responses
- **401 Unauthorized**
- **error_type**: unauthorized_credentials
- **error_message**: Unauthorized credentials.
- **error_url**: https://stytch.com/docs/api/errors/401
- **429 Too Many Requests**
- **error_type**: too_many_requests
- **error_message**: Too many requests have been made.
- **error_url**: https://stytch.com/docs/api/errors/429
- **500 Internal Server Error**
- **error_type**: internal_server_error
- **error_message**: Oops, something seems to have gone wrong, please reach out to support@stytch.com to let us know what went wrong.
- **error_url**: https://stytch.com/docs/api/errors/500
```
--------------------------------
### Get Session Info
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/sessions/get-session-sync
Retrieves session details along with a boolean indicating if the data came from the cache. If `fromCache` is true, it means the session object is from the cache and a state refresh is currently in progress.
```APIDOC
## GET /sessions/me
### Description
Retrieves session details and a boolean indicating if the data originated from the cache. If `fromCache` is true, the session object is from the cache, and a state refresh is in progress.
### Method
GET
### Endpoint
`/sessions/me` (Implicitly called by SDK)
### Parameters
None
### Request Example
```jsx
import { useStytch } from '@stytch/react';
export const SessionInfoDisplay = () => {
const stytch = useStytch();
const sessionInfo = stytch.session.getInfo();
return (
{sessionInfo.session ? (
Session ID: {sessionInfo.session.session_id}
) : (
No active session
)}
Data from cache: {sessionInfo.fromCache ? 'Yes' : 'No'}
);
};
```
### Response
#### Success Response (200)
- **session** (object | null) - The session object, or null if no session is active.
- **session_id** (string) - A unique identifier for a specific Session.
- **user_id** (string) - The unique ID of the affected User.
- **authentication_factors** (array[objects]) - An array of different authentication factors that comprise a Session.
- **started_at** (string) - The timestamp when the Session was created (RFC 3339 format, UTC).
- **last_accessed_at** (string) - The timestamp when the Session was last accessed (RFC 3339 format, UTC).
- **expires_at** (string) - The timestamp when the Session expires (RFC 3339 format, UTC).
- **attributes** (object) - Provided attributes help with fraud detection.
- **ip_address** (string) - The IP address of the user.
- **user_agent** (string) - The user agent of the User.
- **custom_claims** (map) - The custom claims map for a Session.
- **roles** (array[string]) - A list of the roles associated with the session.
- **fromCache** (boolean) - True if the session data was retrieved from the cache, false otherwise.
#### Response Example
```json
{
"session": {
"session_id": "session-live-12345abcde",
"user_id": "user-live-67890fghij",
"authentication_factors": [
{
"delivery_method": "email",
"last_accessed_at": "2023-01-01T12:00:00Z",
"type": "stytch_magic_link"
}
],
"started_at": "2023-01-01T11:00:00Z",
"last_accessed_at": "2023-01-01T12:00:00Z",
"expires_at": "2023-01-01T13:00:00Z",
"attributes": {
"ip_address": "192.168.1.1",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
},
"custom_claims": {
"is_admin": true
},
"roles": ["admin", "editor"]
},
"fromCache": true
}
```
```
--------------------------------
### Start OAuth Authorization with Stytch React SDK
Source: https://stytch.com/docs/api-reference/consumer/frontend-sdks/react/methods/connected-apps/start-oauth-authorization
Initiates the OAuth authorization flow by calling the `oauthAuthorizeStart` method from the Stytch React SDK. This function requires a client ID, redirect URI, response type, and desired scopes. It handles the asynchronous nature of the request and includes basic error logging.
```jsx
import { useState } from 'react';
import { useStytch } from '@stytch/react';
export const OAuthAuthorizeStart = () => {
const stytch = useStytch();
const [loading, setLoading] = useState(false);
const [result] = useState(null);
const startOAuthAuthorization = async () => {
setLoading(true);
try {
await stytch.idp.oauthAuthorizeStart({
client_id: '${exampleConnectedAppClientID}',
redirect_uri: 'https://example.com/callback',
response_type: 'code',
scopes: ['openid', 'profile', 'email'],
prompt: 'consent',
});
} catch (error) {
console.error('Error starting OAuth authorization:', error);
} finally {
setLoading(false);
}
};
return (