diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7b1f6158d2..398002e105 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -439,18 +439,18 @@ console.log('ignored') ### `` -The `` component is used to number a set of instructions with an outcome. It uses the highest heading available in the component to denote each step. Can be used with `h3` headings. +The `` component is used to number a set of instructions with an outcome. It uses the highest heading available in the component to denote each step. Can be used with `h2` and `h3` headings. ```mdx -### Step 1 +## Step 1 Do these actions to complete Step 1. -### Another step +## Another step -#### A heading inside a step +### A heading inside a step Do these actions to complete Step 2. @@ -575,7 +575,7 @@ The `` component is used at the beginning of a tutorial-type con - Install `@clerk/nextjs` - Set up your environment keys to test your app locally -- Add `` to your application +- Add `` to your application - Use Clerk middleware to implement route-specific authentication - Create a header with Clerk components for users to sign in and out diff --git a/docs/_partials/clerk-provider.mdx b/docs/_partials/clerk-provider.mdx new file mode 100644 index 0000000000..d64638d8f5 --- /dev/null +++ b/docs/_partials/clerk-provider.mdx @@ -0,0 +1 @@ +The [``](/docs/components/clerk-provider) component provides session and user context to Clerk's hooks and components. It's recommended to wrap your entire app at the entry point with `` to make authentication globally accessible. See the [reference docs](/docs/components/clerk-provider) for other configuration options. diff --git a/docs/_partials/expo/oauth-custom-flow.mdx b/docs/_partials/expo/oauth-custom-flow.mdx new file mode 100644 index 0000000000..81f09bee6c --- /dev/null +++ b/docs/_partials/expo/oauth-custom-flow.mdx @@ -0,0 +1,58 @@ +The following example demonstrates how to create a custom OAuth sign-in flow for [Google accounts](/docs/authentication/social-connections/google). + +```tsx {{ filename: 'app/(auth)/sign-in.tsx', collapsible: true }} +import React from 'react' +import * as WebBrowser from 'expo-web-browser' +import { Text, View, Button } from 'react-native' +import { Link } from 'expo-router' +import { useOAuth } from '@clerk/clerk-expo' +import * as Linking from 'expo-linking' + +export const useWarmUpBrowser = () => { + React.useEffect(() => { + // Warm up the android browser to improve UX + // https://docs.expo.dev/guides/authentication/#improving-user-experience + void WebBrowser.warmUpAsync() + return () => { + void WebBrowser.coolDownAsync() + } + }, []) +} + +WebBrowser.maybeCompleteAuthSession() + +export default function Page() { + useWarmUpBrowser() + + const { startOAuthFlow } = useOAuth({ strategy: 'oauth_google' }) + + const onPress = React.useCallback(async () => { + try { + const { createdSessionId, signIn, signUp, setActive } = await startOAuthFlow({ + redirectUrl: Linking.createURL('/dashboard', { scheme: 'myapp' }), + }) + + // If sign in was successful, set the active session + if (createdSessionId) { + setActive!({ session: createdSessionId }) + } else { + // Use signIn or signUp returned from startOAuthFlow + // for next steps, such as MFA + } + } catch (err) { + // See https://clerk.com/docs/custom-flows/error-handling + // for more info on error handling + console.error(JSON.stringify(err, null, 2)) + } + }, []) + + return ( + + + Home + + + ) } @@ -69,10 +69,10 @@ The following example shows two files: ```jsx {{ filename: 'app/sign-up/sso-callback/page.tsx' }} import { AuthenticateWithRedirectCallback } from '@clerk/nextjs' - export default function SSOCallback() { + export default function Page() { // Handle the redirect flow by rendering the // prebuilt AuthenticateWithRedirectCallback component. - // This is the final step in the custom SAML flow. + // This is the final step in the custom Enterprise SSO flow. return } ``` @@ -80,13 +80,13 @@ The following example shows two files: -## SAML account transfer flows +## Enterprise account transfer flows -It is common for users who are authenticating with SAML to use a sign-in button when they mean to sign-up, and vice versa. For those cases, the `SignIn` and `SignUp` objects have a `transferable` status that indicates whether the user can be transferred to the other flow. +It is common for users who are authenticating with an enterprise account to use a sign-in button when they mean to sign-up, and vice versa. For those cases, the `SignIn` and `SignUp` objects have a `transferable` status that indicates whether the user can be transferred to the other flow. **If you would like to keep your sign-in and sign-up flows completely separate, then you can skip this section.** -The following example demonstrates how to handle these cases in your sign-in flow. To apply the same logic to the sign-up flow, simply replace `signIn.authenticateWithRedirect()` with `signUp.authenticateWithRedirect()` in your code. +The following example demonstrates how to handle these cases in your sign-in flow. To apply the same logic to the sign-up flow, simply replace [`signIn.authenticateWithRedirect()`][sign-in-redirect] with [`signUp.authenticateWithRedirect()`][sign-up-redirect] in your code. @@ -96,13 +96,13 @@ The following example demonstrates how to handle these cases in your sign-in flo import * as React from 'react' import { useSignIn, useSignUp } from '@clerk/nextjs' - export default function SAMLSignIn() { + export default function Page() { const { signIn } = useSignIn() const { signUp, setActive } = useSignUp() if (!signIn || !signUp) return null - const signInWithSAML = (e: React.FormEvent) => { + const signInWithEnterpriseSSO = (e: React.FormEvent) => { e.preventDefault() const email = (e.target as HTMLFormElement).email.value @@ -110,7 +110,7 @@ The following example demonstrates how to handle these cases in your sign-in flo signIn .authenticateWithRedirect({ identifier: email, - strategy: 'saml', + strategy: 'enterprise_sso', redirectUrl: '/sso-callback', redirectUrlComplete: '/', }) @@ -127,7 +127,7 @@ The following example demonstrates how to handle these cases in your sign-in flo if (!signIn || !signUp) return null // If the user has an account in your application, but does not yet - // have a SAML account connected to it, you can transfer the SAML + // have a enterprise account connected to it, you can transfer the enterprise // account to the existing user account. const userExistsButNeedsToSignIn = signUp.verifications.externalAccount.status === 'transferable' && @@ -143,9 +143,9 @@ The following example demonstrates how to handle these cases in your sign-in flo } } - // If the user has a SAML account but does not yet + // If the user has a enterprise account but does not yet // have an account in your app, you can create an account - // for them using the SAML information. + // for them using the enterprise account's information. const userNeedsToBeCreated = signIn.firstFactorVerification.status === 'transferable' if (userNeedsToBeCreated) { @@ -160,18 +160,22 @@ The following example demonstrates how to handle these cases in your sign-in flo } } else { // If the user has an account in your application - // and has an SAML account connected to it, you can sign them in. - signInWithSAML(e) + // and has an enterprise account connected to it, you can sign them in. + signInWithEnterpriseSSO(e) } } return (
handleSignIn(e)}> - +
) } ```
+ +[sign-in-redirect]: /docs/references/javascript/sign-in/authenticate-with#authenticate-with-redirect + +[sign-up-redirect]: /docs/references/javascript/sign-up/authenticate-with#authenticate-with-redirect diff --git a/docs/custom-flows/google-one-tap.mdx b/docs/custom-flows/google-one-tap.mdx index 0023351877..d072ead81d 100644 --- a/docs/custom-flows/google-one-tap.mdx +++ b/docs/custom-flows/google-one-tap.mdx @@ -10,11 +10,11 @@ description: Learn how to build a custom Google One Tap authentication flow usin This guide will walk you through how to build a custom Google One Tap authentication flow. - ### Enable Google as a social connection + ## Enable Google as a social connection To use Google One Tap with Clerk, follow the steps in the [dedicated guide](/docs/authentication/social-connections/google#configuring-google-social-connection) to configure Google as a social connection in the Clerk Dashboard using custom credentials. - ### Create the Google One Tap authentication flow + ## Create the Google One Tap authentication flow To authenticate users with Google One Tap, you must: diff --git a/docs/custom-flows/manage-sms-based-mfa.mdx b/docs/custom-flows/manage-sms-based-mfa.mdx index a3f45b5d15..34d75f7092 100644 --- a/docs/custom-flows/manage-sms-based-mfa.mdx +++ b/docs/custom-flows/manage-sms-based-mfa.mdx @@ -13,14 +13,14 @@ One of the options that Clerk supports for MFA is **SMS verification codes**. Th > To learn how to build a custom flow for managing authenticator app (TOTP) MFA, see the [dedicated guide](/docs/custom-flows/manage-totp-based-mfa). - ### Enable multi-factor authentication + ## Enable multi-factor authentication For your users to be able to enable MFA for their account, you need to enable MFA as an MFA authentication strategy in your Clerk application. 1. In the Clerk Dashboard, navigate to the [**Multi-factor**](https://dashboard.clerk.com/last-active?path=user-authentication/multi-factor) page. 1. Enable **SMS verification code** and **Backup codes** and select **Save**. - ### Create the multi-factor management flow + ## Create the multi-factor management flow This example is written for Next.js App Router but it can be adapted for any React meta framework, such as Remix. @@ -33,7 +33,7 @@ One of the options that Clerk supports for MFA is **SMS verification codes**. Th - ```tsx {{ filename: '/app/account/manage-mfa/page.tsx', collapsible: true }} + ```tsx {{ filename: 'app/account/manage-mfa/page.tsx', collapsible: true }} 'use client' import * as React from 'react' @@ -222,7 +222,7 @@ One of the options that Clerk supports for MFA is **SMS verification codes**. Th - ```tsx {{ filename: '/app/account/add-phone/page.tsx', collapsible: true }} + ```tsx {{ filename: 'app/account/add-phone/page.tsx', collapsible: true }} 'use client' import * as React from 'react' diff --git a/docs/custom-flows/manage-totp-based-mfa.mdx b/docs/custom-flows/manage-totp-based-mfa.mdx index 5a08c5d936..9710cfe585 100644 --- a/docs/custom-flows/manage-totp-based-mfa.mdx +++ b/docs/custom-flows/manage-totp-based-mfa.mdx @@ -13,14 +13,15 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( > To learn how to build a custom flow for managing SMS MFA, see the [dedicated guide](/docs/custom-flows/manage-sms-based-mfa). - ### Enable multi-factor authentication + ## Enable multi-factor authentication For your users to be able to enable MFA for their account, you need to enable MFA as an MFA authentication strategy in your Clerk application. 1. In the Clerk Dashboard, navigate to the [**Multi-factor**](https://dashboard.clerk.com/last-active?path=user-authentication/multi-factor) page. - 1. Enable **Authenticator application** and **Backup codes** and select **Save**. + 1. Enable **Authenticator application** and **Backup codes**. + 1. Select **Save**. - ### Create the multi-factor management flow + ## Create the multi-factor management flow @@ -35,7 +36,7 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( - ```tsx {{ filename: '/app/account/manage-mfa/page.tsx', collapsible: true }} + ```tsx {{ filename: 'app/account/manage-mfa/page.tsx', collapsible: true }} 'use client' import * as React from 'react' @@ -157,7 +158,7 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( - ```tsx {{ filename: '/app/account/manage-mfa/add/page.tsx', collapsible: true }} + ```tsx {{ filename: 'app/account/manage-mfa/add/page.tsx', collapsible: true }} 'use client' import { useUser } from '@clerk/nextjs' @@ -259,7 +260,7 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( }) { return ( <> -

Backup codes

+

Verification was a success!

Save this list of backup codes somewhere safe in case you need to access your account in @@ -304,32 +305,80 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( ``` + + ### Force MFA (optional) + + While Clerk does not natively enforce MFA for all users, you can implement this functionality by using `clerkMiddleware()` to check whether a user has MFA enabled. + + The following example demonstrates how to force MFA for all users. It uses `clerkMiddleware()` to intercept all requests and check whether a user has MFA enabled. If the user does not have MFA enabled, `clerkMiddleware()` redirects them to the `/mfa` page where they can set up MFA. + + ```tsx {{ filename: 'middleware.ts', collapsible: true }} + import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server' + import { NextResponse } from 'next/server' + + const isMFARoute = createRouteMatcher(['/account/manage-mfa/add(.*)']) + const isSignInRoute = createRouteMatcher(['/sign-in(.*)']) + + export default clerkMiddleware(async (auth, req) => { + const { userId } = await auth() + + // Redirect to homepage if the user is signed in and on the sign-in page + if (userId !== null && isSignInRoute(req) && !isMFARoute(req)) { + return NextResponse.redirect(new URL('/', req.url)) + } + + // Check if the user is signed in and not on the MFA page + if (userId !== null && !isMFARoute(req)) { + const res = await fetch(`https://api.clerk.com/v1/users/${userId}`, { + headers: { + Authorization: `Bearer ${process.env.CLERK_SECRET_KEY}`, + }, + }) + + const userData = await res.json() + + // Redirect to MFA setup page if MFA is not enabled + if (userData.two_factor_enabled === false) { + return NextResponse.redirect(new URL('/account/manage-mfa/add', req.url)) + } + } + }) + + export const config = { + matcher: [ + // Skip Next.js internals and all static files, unless found in search params + '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', + // Always run for API routes + '/(api|trpc)(.*)', + ], + } + ``` ### Before you start - Install `expo-checkbox` for the UI and `@clerk/types` for type definitions. + Install `expo-checkbox` for the UI and `react-native-qr-svg` for the QR code. ```bash {{ filename: 'terminal' }} - npm install expo-checkbox @clerk/types + npm install expo-checkbox react-native-qr-svg ``` ```bash {{ filename: 'terminal' }} - yarn add expo-checkbox @clerk/types + yarn add expo-checkbox react-native-qr-svg ``` ```bash {{ filename: 'terminal' }} - pnpm add expo-checkbox @clerk/types + pnpm add expo-checkbox react-native-qr-svg ``` ### Build the flow - To allow users to configure MFA, you will create a basic dashboard. + To allow users to configure their MFA settings, you'll create a basic dashboard. - This example consists of three pages: + The following example consists of three pages: - The layout page that checks if the user is signed in - The page where users can manage their account, including their MFA settings @@ -339,7 +388,8 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( - Start by creating the `(dashboard)` route group and adding the following code to the layout: + 1. Create the `(dashboard)` route group. This groups your account page and the "Add TOTP MFA" page. + 1. Create a `_layout.tsx` file with the following code. The [`useAuth()`](/docs/references/react/use-auth) hook is used to check if the user is signed in. If the user isn't signed in, they'll be redirected to the sign-in page. ```tsx {{ filename: 'app/(dashboard)/_layout.tsx' }} import { Redirect, Stack } from 'expo-router' @@ -358,16 +408,17 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( - Add a basic account page to the `(dashboard)` route group that shows users whether or not MFA is enabled, and allows them to add MFA with an authenticator app. + In the `(dashboard)` group, create an `account.tsx` file with the following code. This page shows users whether or not MFA is enabled, and allows them to add MFA with an authenticator app. ```tsx {{ filename: 'app/(dashboard)/account.tsx', collapsible: true }} import React from 'react' import { useUser } from '@clerk/clerk-expo' - import { Link } from 'expo-router' - import { View, Text, Button, TouchableOpacity, FlatList } from 'react-native' + import { useRouter } from 'expo-router' + import { View, Text, Button, FlatList } from 'react-native' import { BackupCodeResource } from '@clerk/types' export default function ManageTOTPMfa() { + const router = useRouter() const [backupCodes, setBackupCodes] = React.useState(undefined) const [loading, setLoading] = React.useState(false) @@ -395,7 +446,7 @@ One of the options that Clerk supports for MFA is **Authenticator applications ( const MFAEnabled = () => { return ( - + TOTP via authentication app enabled - + + + {actionData ? ( +

+          {JSON.stringify(actionData, null, 2)}
+        
+ ) : null} +
+ ) +} +``` diff --git a/docs/references/react-router/library-mode.mdx b/docs/references/react-router/library-mode.mdx new file mode 100644 index 0000000000..4d04824993 --- /dev/null +++ b/docs/references/react-router/library-mode.mdx @@ -0,0 +1,128 @@ +--- +title: React Router library mode +description: Learn how to use Clerk with React Router in library mode to add authentication to your application. +--- + +> [!WARNING] +> The React Router SDK is currently in beta. + + + - Install `@clerk/react-router` + - Set your Clerk API keys + - Add `` + - Protect your pages + + +React Router can be used as a framework or as a standalone library. This guide explains how to add React Router authentication to an existing React application using library mode. To use React Router as a framework instead, see the [React Router quickstart](/docs/quickstarts/react-router). + + + ## Install `@clerk/react-router` + + Clerk's [React Router SDK](/docs/references/react-router/overview) provides prebuilt components, hooks, and stores to make it easy to integrate authentication and user management in your React Router app. + + Run the following command to install the SDK: + + + ```bash {{ filename: 'terminal' }} + npm install @clerk/react-router + ``` + + ```bash {{ filename: 'terminal' }} + yarn add @clerk/react-router + ``` + + ```bash {{ filename: 'terminal' }} + pnpm add @clerk/react-router + ``` + + + ## Set your Clerk API keys + + > [!NOTE] + > You will not need the Clerk Secret Key in React Router's library mode, as it should never be used on the client-side. + + + Add your Clerk Publishable Key to your `.env` file. This key can always be retrieved from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page of the Clerk Dashboard. + + + + 1. In the Clerk Dashboard, navigate to the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page. + 1. In the **Quick Copy** section, copy your Clerk Publishable Key. + 1. Add your key to your `.env` file. + + The final result should resemble the following: + + + ```env {{ filename: '.env' }} + VITE_CLERK_PUBLISHABLE_KEY={{pub_key}} + ``` + + ## Add `` to your app + + + + You must pass your Publishable Key as a prop, as shown in the following example: + + ```tsx {{ filename: 'src/main.tsx', mark: [4, 8, [13, 17]] }} + import { StrictMode } from 'react' + import { createRoot } from 'react-dom/client' + import { BrowserRouter, Routes, Route } from 'react-router' + import { ClerkProvider } from '@clerk/react-router' + import './index.css' + import App from './App.tsx' + + const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY + + createRoot(document.getElementById('root')!).render( + + + + + } /> + + + + , + ) + ``` + + ## Create a header with Clerk components + + You can control which content signed-in and signed-out users can see with the [prebuilt control components](/docs/components/overview#what-are-control-components). The following example creates a header using the following components: + + - [``](/docs/components/control/signed-in): Children of this component can only be seen while **signed in**. + - [``](/docs/components/control/signed-out): Children of this component can only be seen while **signed out**. + - [``](/docs/components/user/user-button): Shows the signed-in user's avatar. Selecting it opens a dropdown menu with account management options. + - [``](/docs/components/unstyled/sign-in-button): An unstyled component that links to the sign-in page or displays the sign-in modal. + + ```tsx {{ filename: 'src/App.tsx' }} + import { SignInButton, SignedIn, SignedOut, UserButton } from '@clerk/react-router' + + export default function App() { + return ( +
+ + + + + + +
+ ) + } + ``` +
diff --git a/docs/references/react-router/overview.mdx b/docs/references/react-router/overview.mdx new file mode 100644 index 0000000000..b7669134cf --- /dev/null +++ b/docs/references/react-router/overview.mdx @@ -0,0 +1,33 @@ +--- +title: Clerk React Router SDK +description: Learn how to use Clerk to quickly and easily add secure authentication and user management to your React Router application. +--- + +> [!WARNING] +> The React Router SDK is currently in beta. + +Clerk makes it simple to add authentication to your React Router application. This reference lists the features and methods available in Clerk's React Router SDK. + +## Client-side helpers + +The Clerk React Router SDK is built on top of the Clerk React SDK and provides access to all of Clerk React's hooks. These hooks give you access to the [`Clerk`](/docs/references/javascript/clerk/clerk) object and a set of useful helper methods for signing in and signing up. Learn more about these hooks in the [React SDK reference](/docs/references/react/overview). + + + +## Server-side helpers + +The following references show how to integrate Clerk features into applications using React Router server functions and API routes. + +- [`getAuth()`](/docs/references/react-router/get-auth) +- [`rootAuthLoader()`](/docs/references/react-router/root-auth-loader) + +### `Auth` object + +The `getAuth()` method returns an `Auth` object. This JavaScript object contains important information like the current user's session ID, user ID, and organization ID. Learn more about the [`Auth` object](/docs/references/nextjs/auth-object){{ target: '_blank' }}. + +## React Router implementations + +React Router can be integrated with Clerk in two ways: + +- As a framework (recommended): Configure your app using [Clerk's React Router SDK](/docs/quickstarts/react-router) +- As a library: Manually integrate React Router into your React + Vite app using [library mode](/docs/references/react-router/library-mode) diff --git a/docs/references/react-router/read-session-data.mdx b/docs/references/react-router/read-session-data.mdx new file mode 100644 index 0000000000..23398a1e38 --- /dev/null +++ b/docs/references/react-router/read-session-data.mdx @@ -0,0 +1,54 @@ +--- +title: Read session and user data in your React Router app with Clerk +description: Learn how to use Clerk's hooks and helpers to access the active session and user data in your React Router application. +--- + +Clerk provides a set of [hooks and helpers](/docs/references/react-router/overview#client-side-helpers) that you can use to access the active session and user data in your React Router application. Here are examples of how to use these helpers in both the client and server-side to get you started. + +## Server-side + +To access active session and user data on the server-side, use the `getAuth()` helper. See the [reference documentation](/docs/references/react-router/get-auth) for more information, including code examples. + +## Client-side + +To access active session and user data on the client-side, use Clerk's `useAuth()` and `useUser()` hooks. + +### `useAuth()` + +The [`useAuth()`](/docs/references/react/use-auth){{ target: '_blank' }} hook provides information about the current auth state, as well as helper methods to manage the current active session. The hook returns `userId`, which can be used to protect your routes, as shown in the following example: + +```tsx {{ filename: 'app/routes/use-auth.tsx' }} +import { useAuth } from '@clerk/react-router' + +export default function UseAuthPage() { + const { isLoaded, userId } = useAuth() + + // Return null if the user signs out while on the page + // or if the auth state is still loading + if (!isLoaded || !userId) { + return null + } + + return
Hello, {userId}!
+} +``` + +### `useUser()` + +The [`useUser()`](/docs/references/react/use-user){{ target: '_blank' }} hook provides the current user's [`User`](/docs/references/javascript/user/user){{ target: '_blank' }} object, which holds all of the information for a user of your application and provides a set of methods to manage their account. + +```tsx {{ filename: 'app/routes/use-user.tsx' }} +import { useUser } from '@clerk/react-router' + +export default function UseUserPage() { + const { isLoaded, isSignedIn, user } = useUser() + + // Return null if the user signs out while on the page + // or if the auth state is still loading + if (!isLoaded || !isSignedIn) { + return null + } + + return
Hello, {user.firstName}!
+} +``` diff --git a/docs/references/react-router/root-auth-loader.mdx b/docs/references/react-router/root-auth-loader.mdx new file mode 100644 index 0000000000..cf465b889e --- /dev/null +++ b/docs/references/react-router/root-auth-loader.mdx @@ -0,0 +1,159 @@ +--- +title: '`rootAuthLoader()`' +description: The rootAuthLoader() function configures Clerk to handle authentication state for React Router routes. +--- + +The `rootAuthLoader()` function configures Clerk to handle authentication state for React Router routes, allowing easy access to user session information in your app. + +## Configure `rootAuthLoader()` + +In your `root.tsx` file, add `rootAuthLoader` to the `loader` function. If your app doesn't have a loader function yet, you'll need to add it manually. + +```tsx {{ filename: 'app/root.tsx' }} +import { rootAuthLoader } from '@clerk/react-router/ssr.server' +import type { Route } from './+types/root' + +export async function loader(args: Route.LoaderArgs) { + return rootAuthLoader(args) +} +``` + +You can also pass [options](#root-auth-loader-options) to the `rootAuthLoader()` as the second argument. + +```tsx {{ filename: 'app/root.tsx', mark: [5] }} +import { rootAuthLoader } from '@clerk/react-router/ssr.server' +import type { Route } from './+types/root' + +export async function loader(args: Route.LoaderArgs) { + return rootAuthLoader(args, { signInUrl: '/sign-in' }) +} +``` + +### Loading additional data + +If you need to load additional data, you can pass your loader directly to `rootAuthLoader()` as the second argument. The options object is passed as the third argument. + +```tsx {{ filename: 'app/root.tsx', mark: [7, 13] }} +import { rootAuthLoader } from '@clerk/react-router/ssr.server' +import type { Route } from './+types/root' + +export async function loader(args: Route.LoaderArgs) { + return rootAuthLoader( + args, + ({ request, context, params }) => { + // Loader + const { userId } = request.auth + + return { userId } + }, + { signInUrl: '/sign-in' }, // Options + ) +} +``` + +## `rootAuthLoader()` options + + + - `secretKey?` + - `string` + + The Clerk Secret Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. + + --- + + - `jwtKey?` + - `string` + + The PEM public key from the **[**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page -> Show JWT public key -> PEM Public Key** section in the Clerk Dashboard. For more information, refer to [Manual JWT verification](/docs/backend-requests/handling/manual-jwt). + + --- + + - `publishableKey?` + - `string` + + The Clerk Publishable Key from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. + + --- + + - `domain?` + - `string` + + The domain of a [satellite application](/docs/advanced-usage/satellite-domains) in a multi-domain setup. + + --- + + - `isSatellite?` + - `boolean` + + Whether the instance is a satellite domain in a multi-domain setup. Defaults to `false`. + + --- + + - `proxyUrl?` + - `string` + + The proxy URL from a multi-domain setup. + + --- + + - `sdkMetadata?` + - `{ name: string, version: string }` + + Metadata about the SDK. + + --- + + - `telemetry?` + - `{ disabled: boolean, debug: boolean }` + + [Telemetry](/docs/telemetry) configuration. + + --- + + - `userAgent?` + - `string` + + The User-Agent request header passed to the Clerk API. + + --- + + - `apiUrl?` + - `string` + + The [Clerk Backend API](/docs/reference/backend-api){{ target: '_blank' }} endpoint. Defaults to `'https://api.clerk.com'`. + + --- + + - `apiVersion?` + - `string` + + The version passed to the Clerk API. Defaults to `'v1'`. + + --- + + - `audience?` + - `string | string[]` + + A string or list of [audiences](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3). + + --- + + - `authorizedParties?` + - `string[]` + + An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example: `['http://localhost:3000', 'https://example.com']` + + --- + + - `signInUrl?` + - `string` + + The full URL or path to the sign in page. Use this property to provide the target of the 'Sign in' link that's rendered. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. + + --- + + - `signUpUrl?` + - `string` + + The full URL or path to the sign up page. Use this property to provide the target of the 'Sign up' link that's rendered. It's recommended to use [the environment variable](/docs/deployments/clerk-environment-variables#sign-in-and-sign-up-redirects) instead. +
diff --git a/docs/references/react/add-react-router.mdx b/docs/references/react/add-react-router.mdx deleted file mode 100644 index 469ba35c67..0000000000 --- a/docs/references/react/add-react-router.mdx +++ /dev/null @@ -1,334 +0,0 @@ ---- -title: Add React Router to your Clerk-powered React application -description: Learn how to add React Router to your React application using their Data API router. ---- - - - - Install `react-router-dom` - - Create components for your routes - - Create layouts - - Wire layouts and routes up with `createBrowserRouter` - - -> [!WARNING] -> This tutorial is written for [React Router 6](https://reactrouter.com/6.28.0/home) and doesn't support [loaders](https://reactrouter.com/6.28.0/route/loader) and [actions](https://reactrouter.com/6.28.0/route/action). - -Learn how to add React Router to your application using React Router's new Data API router. This tutorial will cover configuring layouts and setting up protected routes. - - - ### Install `react-router-dom` - - React Router's `react-router-dom` is a mature, battle tested routing package for React that gives you many options. As it is the most popular routing option, it will be used for this guide. - - - ```bash {{ filename: 'terminal' }} - npm install react-router-dom - ``` - - ```bash {{ filename: 'terminal' }} - yarn add react-router-dom - ``` - - ```bash {{ filename: 'terminal' }} - pnpm add react-router-dom - ``` - - - ### Create components for your routes - - The exact routes you will need depends on your application. For this guide, you will create `/`, `/contact`, `/dashboard`, `/sign-in`, and `sign-up` routes. The `/dashboard` route will contain a default route (`/dashbard/`) and an invoices route (`/dashboard/invoices`). The first step will be creating basic components for these routes. - - Use the tabs below to find the example components and recreate these files using the path from each tab. - - - ```tsx {{ filename: 'src/routes/index.tsx' }} - import { Link } from 'react-router-dom' - - export default function IndexPage() { - return ( -
-

This is the index page

-
-
    -
  • - Sign Up -
  • -
  • - Sign In -
  • -
  • - Contact -
  • -
  • - Dashboard -
  • -
-
-
- ) - } - ``` - - ```tsx {{ filename: 'src/routes/contact.tsx' }} - import { Link } from 'react-router-dom' - - export default function ContactPage() { - return ( - <> -

Contact

-

- This is a public page meant to contain a contact form and other related contact details. -

-
    -
  • - Return to Index -
  • -
  • - Dashboard -
  • -
- - ) - } - ``` - - ```tsx {{ filename: 'src/routes/sign-in.tsx' }} - import { SignIn } from '@clerk/clerk-react' - - export default function SignInPage() { - return - } - ``` - - ```tsx {{ filename: 'src/routes/sign-up.tsx' }} - import { SignUp } from '@clerk/clerk-react' - - export default function SignUpPage() { - return - } - ``` - - ```tsx {{ filename: 'src/routes/dashboard.tsx' }} - import { Link } from 'react-router-dom' - - export default function DashboardPage() { - return ( - <> -

Dashboard page

-

This is a protected page.

- -
    -
  • - Invoices -
  • -
  • - Return to index -
  • -
- - ) - } - ``` - - ```tsx {{ filename: 'src/routes/dashboard.invoices.tsx' }} - import { Link } from 'react-router-dom' - - export default function InvoicesPage() { - return ( - <> -

Invoices page

-

This is a protected page.

- -
    -
  • - Dashboard -
  • -
  • - Return to index -
  • -
- - ) - } - ``` -
- - ### Create layouts - - You're going to create two layouts for your application. One will mount [``](/docs/components/clerk-provider) and act as a top level layout. It will also be a place for a header, footer, and other standard elements for your application. - - The second layout will be non-rendering and will protect everything in the `/dashboard` route. This avoids the need for per-page auth checks or for using Clerk's control components. - - - ```tsx {{ filename: 'src/layouts/root-layout.tsx' }} - import { Link, Outlet, useNavigate } from 'react-router-dom' - import { ClerkProvider, SignedIn, SignedOut, UserButton } from '@clerk/clerk-react' - - const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY - - if (!PUBLISHABLE_KEY) { - throw new Error('Missing Publishable Key') - } - - export default function RootLayout() { - const navigate = useNavigate() - - return ( - navigate(to)} - routerReplace={(to) => navigate(to, { replace: true })} - publishableKey={PUBLISHABLE_KEY} - > -
-
-
-

Clerk + React + React Router App

-
- - - - - Sign In - -
-
-
- -
-
- ) - } - ``` - - ```tsx {{ filename: 'src/layouts/dashboard-layout.tsx' }} - import * as React from 'react' - import { useAuth } from '@clerk/clerk-react' - import { Outlet, useNavigate } from 'react-router-dom' - - export default function DashboardLayout() { - const { userId, isLoaded } = useAuth() - const navigate = useNavigate() - - console.log('test', userId) - - React.useEffect(() => { - if (isLoaded && !userId) { - navigate('/sign-in') - } - }, [isLoaded]) - - if (!isLoaded) return 'Loading...' - - return - } - ``` -
- - #### Key Takeaways - - - The new root-layout.tsx has a simple header that includes the `` and a link to the `/sign-in` page instead of a ``. The rendering of these is controlled by the `` and `` control components. This is very similar to the [Embed the `` and ``](/docs/quickstarts/react#embed-the-user-button-and-sign-in-button) step from the [React Quickstart](/docs/quickstarts/react). - - Both the layouts contain an `` component from `react-router-dom`. This behaves similar to `{children}` in Next.js or more generic React components. You will take advantage of this component in the next step. - - ### Wire layouts and routes up with `createBrowserRouter` - - With all the routes and layouts you need created, you now need to wire up the layouts and the routes with the `createBrowserRouter` function from `react-router-dom`. This will use the Data API (aka Data Router) to configure your application. - - You can start by removing `src/App.tsx`—the contents of that file were moved to `src/layouts/root-layout.tsx`. - - In `src/main.tsx`, import `RouterProvider` and `createBrowserRouter()` from `react-router-dom`, as well as all of the default components from the layouts and routes you created. Replace the contents inside of `` with only ` `. Lastly, you will build the `router` using `createBrowserRouter()`. - - ```tsx {{ filename: 'src/main.tsx' }} - import React from 'react' - import ReactDOM from 'react-dom/client' - import './index.css' - import { RouterProvider, createBrowserRouter } from 'react-router-dom' - - // Import the layouts - import RootLayout from './layouts/root-layout' - import DashboardLayout from './layouts/dashboard-layout' - - // Import the components - import IndexPage from './routes' - import ContactPage from './routes/contact' - import SignInPage from './routes/sign-in' - import SignUpPage from './routes/sign-up' - import DashboardPage from './routes/dashboard' - import InvoicesPage from './routes/dashboard.invoices' - - const router = createBrowserRouter([ - { - element: , - children: [ - { path: '/', element: }, - { path: '/contact', element: }, - { path: '/sign-in/*', element: }, - { path: '/sign-up/*', element: }, - { - element: , - path: 'dashboard', - children: [ - { path: '/dashboard', element: }, - { path: '/dashboard/invoices', element: }, - ], - }, - ], - }, - ]) - - ReactDOM.createRoot(document.getElementById('root')!).render( - - - , - ) - ``` - - Visit [`http://localhost:5173`](http://localhost:5173) and explore your app's pages. - - #### Key Takeaways - - - The top most object in the `router` is the `` component, and everything else is a child. Any child route will be mounted where the `` component is inside the root layout. This wraps the entire application with `` and allows you to add a header, footer, sidebars and other pieces that will be available to the entire application. - - Several routes are direct children of the root layout. These are all public routes. You can use control components like `` or check the `userId` from `useAuth()` if you want to make content protected. - - The `` is child of the root layout, renders nothing, and has a check to see if the `userId` exists. This will confirm that a user is signed in. If the `userId` is not truthy, then the user will be redirected to the `/sign-in` route to sign-in. That protects all pages in the `/dashboard` route. All children of `/dashboard` will be mounted inside of the `` component in the dashboard layout. -
- -Your application is setup with `react-router-dom` and ready for you to add more layouts and routes as needed! If you want to get started using a template from this guide, clone the following repository and then checkout the `integrate-react-router-dom-using-data-router-method` branch. - -- [Clerk + React Quickstart](https://github.com/clerk/clerk-react-quickstart) - -### Next steps - - - - [Customization & Localization](/docs/customization/overview) - - Learn how to customize and localize the Clerk components. - - --- - - - [Authentication Components](/docs/components/authentication/sign-in) - - Learn more about all our authentication components. - - --- - - - [Client Side Helpers](/docs/references/react/use-user) - - Learn more about our client-side helpers and how to use them. - diff --git a/docs/references/react/overview.mdx b/docs/references/react/overview.mdx index 50b72d2f59..0545b4f8a1 100644 --- a/docs/references/react/overview.mdx +++ b/docs/references/react/overview.mdx @@ -1,19 +1,47 @@ --- title: Clerk React SDK -description: Learn how to integrate React into your Clerk application. +description: Learn how to integrate Clerk into your React application using the Clerk React SDK. --- -The Clerk React SDK is a wrapper around the Clerk JavaScript SDK. It is the recommended way to integrate Clerk into your React application. +The React SDK is built on top of the JavaScript SDK, and is the recommended method for integrating Clerk into your React application. -> [!WARNING] -> If you are using Next.js, install the `@clerk/nextjs` package, as `@clerk/clerk-react` is incompatible. See the [Next.js](/docs/references/nextjs/overview) documentation for more information. +## Key features -Clerk React provides React.js implementations of [Clerk components](/docs/components/overview); highly customizable, prebuilt components that you can use to build beautiful user management applications. You can find display components for building [sign-in](/docs/components/authentication/sign-in), [sign-up](/docs/components/authentication/sign-up), [account switching](/docs/components/user/user-button), and [user profile management](/docs/components/user/user-profile) pages as well as flow [control components](/docs/components/control/signed-in) that act as helpers for implementing a seamless authentication experience. +### Pre-built components -Clerk React provides a suite of [custom hooks](/docs/references/react/use-user). These hooks give you access to the [`Clerk` object](/docs/references/javascript/clerk/clerk), and a set of useful helper methods for signing in and signing up. +The React SDK provides access to [Clerk components](/docs/components/overview) for user and organization management, including: -## Setting up Clerk React +- [Sign-in](/docs/components/authentication/sign-in) +- [Sign-up](/docs/components/authentication/sign-up) +- [Account switching](/docs/components/user/user-button) +- [User profile management](/docs/components/user/user-profile) +- [Organization switching](/docs/components/organization/organization-switcher) +- [Organization management](/docs/components/organization/organization-profile) +- [Control components](/docs/components/control/signed-in) -You need to create a Clerk application in the Clerk Dashboard before you can set up Clerk React. For more information, see the [setup guide](/docs/quickstarts/setup-clerk). +### Custom hooks -Once a Clerk application has been created, you can install and start using Clerk React in your application. [The quickstart guide](/docs/quickstarts/react) will have all the information you need to get started. +The React SDK provides access to custom hooks that provide direct access to the [`Clerk` object](/docs/references/javascript/clerk/clerk), a user's [`User` object](/docs/references/javascript/user/user), and helper methods for authentication flows. + + + +## Framework-specific SDKs + +> [!IMPORTANT] +> Clerk provides optimized SDKs for specific React frameworks. If you're using one of the supported frameworks below, you should use its dedicated SDK instead of `@clerk/clerk-react`. +> +> For example, Next.js applications **must** use `@clerk/nextjs` as `@clerk/clerk-react` is not compatible. + +Clerk offers framework-specific SDKs that are customized to provide the better developer experience and integration with each framework's features. Choose the appropriate SDK based on your framework: + +| Framework | Package | Docs | +| - | - | - | +| Next.js | `@clerk/nextjs` | [Next.js SDK](/docs/references/nextjs/overview) | +| React Router | `@clerk/clerk-react-router` | [React Router SDK](/docs/references/react-router/overview) | +| Remix | `@clerk/remix` | [Remix SDK](/docs/references/remix/clerk-app) | +| Astro | `@clerk/astro` | [Astro SDK](/docs/references/astro/overview) | +| Tanstack Start | `@clerk/tanstack-start` | [Tanstack Start SDK](/docs/references/tanstack-start/overview) | + +## Set up Clerk React + +Before you can add Clerk to your React application, you must create a Clerk app in the Clerk Dashboard. To get started, follow the [setup guide](/docs/quickstarts/setup-clerk). Then, follow the [quickstart guide](/docs/quickstarts/react) to set up the React SDK in your app. diff --git a/docs/references/react/use-sign-in.mdx b/docs/references/react/use-sign-in.mdx index c178a6a80d..aa194cb672 100644 --- a/docs/references/react/use-sign-in.mdx +++ b/docs/references/react/use-sign-in.mdx @@ -77,7 +77,7 @@ The `status` property of the `SignIn` object can be one of the following values: | Values | Descriptiom | | - | - | | `complete` | The user has been signed in and custom flow can proceed to `setActive()` to create session. | -| `needs_first_factor` | The First Factor verification is missing. One of `email_link`, `email_code`, `phone_code`, `web3_metamask_signature`, `web3_coinbase_wallet_signature` or `oauth_provider` is required to verify user. See [First Factor](/docs/references/javascript/sign-in/first-factor) for details. | +| `needs_first_factor` | The first factor verification is missing. One of `email_link`, `email_code`, `phone_code`, `web3_metamask_signature`, `web3_coinbase_wallet_signature`, `web3_okx_wallet_signature` or `oauth_provider` is required to verify the user. See [the reference](/docs/references/javascript/sign-in/first-factor) for more information. | | `needs_second_factor` | The Second Factor verification is missing. The Second Factor is an optional step to provide additional verification and includes `phone_code` and `totp`. See [Second Factor](/docs/references/javascript/sign-in/second-factor) for details. | | `needs_identifier` | The user's identifier (email address, phone number, username, etc.) hasn't been provided. | | `needs_new_password` | The user needs to set a new password. | diff --git a/docs/references/redwood/overview.mdx b/docs/references/redwood/overview.mdx index 938bd3f4b0..7c2d5837b7 100644 --- a/docs/references/redwood/overview.mdx +++ b/docs/references/redwood/overview.mdx @@ -1,12 +1,12 @@ --- -title: Use Clerk with RedwoodJS +title: Clerk RedwoodJS SDK description: Learn how to use Clerk to quickly and easily add secure authentication and user management to your RedwoodJS application. --- Learn how to use Clerk to quickly and easily add secure authentication and user management to your RedwoodJS application. - ### Create a RedwoodJS application + ## Create a RedwoodJS application ```bash {{ filename: 'terminal' }} @@ -22,7 +22,7 @@ Learn how to use Clerk to quickly and easily add secure authentication and user ``` - ### Set environment variables + ## Set environment variables Below is an example of an `.env.local` file. @@ -33,14 +33,14 @@ Learn how to use Clerk to quickly and easily add secure authentication and user CLERK_SECRET_KEY={{secret}} ``` - #### Update redwood.toml + ### Update redwood.toml ```toml {{ filename: 'redwood.toml' }} [web] includeEnvironmentVariables = ['CLERK_PUBLISHABLE_KEY'] ``` - ### Set up Redwood auth + ## Set up Redwood auth The next step is to run a Redwood CLI command to install the required packages and generate some boilerplate code: @@ -53,7 +53,7 @@ Learn how to use Clerk to quickly and easily add secure authentication and user You can now access Clerk functions through the Redwood `useAuth()` hook, which is exported from `src/web/auth.tsx`, or you can use the Clerk components directly. - ### Protecting your pages + ## Protecting your pages Below is an example of using the `useAuth()` hook to verify if the user is authenticated. This will open a modal for your user to sign in to their account. @@ -80,7 +80,7 @@ Learn how to use Clerk to quickly and easily add secure authentication and user export default HomePage ``` - ### Using Clerk components directly + ## Using Clerk components directly ```tsx {{ filename: 'index.tsx' }} import { SignInButton, UserButton } from '@clerk/clerk-react' @@ -105,7 +105,7 @@ Learn how to use Clerk to quickly and easily add secure authentication and user ``` -### Next steps +## Next steps Now that you have an application integrated with Clerk, you will want to read the following documentation: diff --git a/docs/references/remix/clerk-app.mdx b/docs/references/remix/clerk-app.mdx index d165a65a56..c1070fc202 100644 --- a/docs/references/remix/clerk-app.mdx +++ b/docs/references/remix/clerk-app.mdx @@ -80,7 +80,14 @@ export default ClerkApp(App) - `allowedRedirectOrigins?` - `Array` - Optional array of domains used to validate against the query param of an auth redirect. If no match is made, the redirect is considered unsafe and the default redirect will be used with a warning passed to the console. + An optional array of domains to validate user-provided redirect URLs against. If no match is made, the redirect is considered unsafe and the default redirect will be used with a warning logged in the console. + + --- + + - `allowedRedirectProtocols?` + - `Array` + + An optional array of protocols to validate user-provided redirect URLs against. If no match is made, the redirect is considered unsafe and the default redirect will be used with a warning logged in the console. [components-ref]: /docs/components/overview diff --git a/docs/references/remix/spa-mode.mdx b/docs/references/remix/spa-mode.mdx index 3c92e3c79b..c0c6de3a04 100644 --- a/docs/references/remix/spa-mode.mdx +++ b/docs/references/remix/spa-mode.mdx @@ -25,7 +25,7 @@ description: Clerk supports Remix SPA mode out-of-the-box. > If you are using Remix with SSR, follow the [Remix quickstart](/docs/quickstarts/remix). - ### Install `@clerk/remix` + ## Install `@clerk/remix` Once you have a Remix application ready, you need to install Clerk's Remix SDK. This gives you access to our prebuilt components and hooks for Remix applications. @@ -43,7 +43,7 @@ description: Clerk supports Remix SPA mode out-of-the-box. ``` - ### Set your environment variables + ## Set your environment variables Add your Clerk Publishable Key to your `.env` file. It can always be retrieved from the [**API keys**](https://dashboard.clerk.com/last-active?path=api-keys) page in the Clerk Dashboard. @@ -64,7 +64,7 @@ description: Clerk supports Remix SPA mode out-of-the-box. VITE_CLERK_PUBLISHABLE_KEY={{pub_key}} ``` - ### Configure `ClerkApp` + ## Configure `ClerkApp` Clerk provides a `ClerkApp` wrapper to provide the authentication state to your React tree. @@ -98,7 +98,7 @@ description: Clerk supports Remix SPA mode out-of-the-box. }) ``` - ### Update your paths through ClerkApp options + ## Update your paths through ClerkApp options Next, add paths to your `ClerkApp` options to control the behavior of the components when you sign in or sign up and when you click on the respective links at the bottom of each component. @@ -110,7 +110,7 @@ description: Clerk supports Remix SPA mode out-of-the-box. }) ``` - ### Protecting your pages + ## Protecting your pages Clerk offers [Control Components](/docs/components/overview) that allow you to protect your pages. These components are used to control the visibility of your pages based on the user's authentication state. @@ -153,7 +153,7 @@ description: Clerk supports Remix SPA mode out-of-the-box. ``` -### Next steps +## Next steps Now that you have an application integrated with Clerk, you will want to read the following documentation: diff --git a/docs/references/ruby/overview.mdx b/docs/references/ruby/overview.mdx index 71b1475fe9..fb9b3491f7 100644 --- a/docs/references/ruby/overview.mdx +++ b/docs/references/ruby/overview.mdx @@ -4,11 +4,11 @@ description: Learn how to integrate Ruby into your Clerk application. --- - ### Create a Clerk application + ## Create a Clerk application You need to create a Clerk application in the Clerk Dashboard before you can set up Clerk Ruby. For more information, see the [setup guide](/docs/quickstarts/setup-clerk). - ### Install Ruby + ## Install Ruby Once a Clerk application has been created, you can install and then start using Clerk Ruby in your application. @@ -30,7 +30,7 @@ description: Learn how to integrate Ruby into your Clerk application. $ gem install clerk-sdk-ruby ``` - ### Instantiate a `Clerk::SDK` instance + ## Instantiate a `Clerk::SDK` instance To access all [Backend API endpoints](/docs/reference/backend-api){{ target: '_blank' }}, you need to instantiate a `Clerk::SDK` instance. @@ -59,7 +59,7 @@ description: Learn how to integrate Ruby into your Clerk application. ) ``` - ### Configuration + ## Configuration The SDK can be configured in three ways: environment variables, configuration singleton and constructor arguments. The priority goes like this: @@ -67,7 +67,7 @@ description: Learn how to integrate Ruby into your Clerk application. - Configuration object - Environment variables - #### Constructor arguments + ### Constructor arguments You can customize each instance of the `Clerk::SDK` object by passing keyword arguments to the constructor: @@ -79,7 +79,7 @@ description: Learn how to integrate Ruby into your Clerk application. ) ``` - #### Configuration object + ### Configuration object If an argument is not provided, the configuration object is looked up, which falls back to the associated environment variable. Here's an example with all supported configuration settings their environment variable equivalents: @@ -94,7 +94,7 @@ description: Learn how to integrate Ruby into your Clerk application. For more information, see [Faraday's documentation](https://lostisland.github.io/faraday/#/). - #### Environment variables + ### Environment variables Here's a list of all environment variables the SDK uses: diff --git a/docs/references/tanstack-start/overview.mdx b/docs/references/tanstack-start/overview.mdx index 59c1d555ca..68a1d12288 100644 --- a/docs/references/tanstack-start/overview.mdx +++ b/docs/references/tanstack-start/overview.mdx @@ -1,5 +1,5 @@ --- -title: "TanStack Start and Clerk" +title: Clerk TanStack Start SDK description: Learn how to use Clerk to quickly and easily add secure authentication and user management to your TanStack Start application. --- diff --git a/docs/security/unauthorized-sign-in.mdx b/docs/security/unauthorized-sign-in.mdx new file mode 100644 index 0000000000..b24a90dc29 --- /dev/null +++ b/docs/security/unauthorized-sign-in.mdx @@ -0,0 +1,41 @@ +--- +title: Unauthorized sign-in +description: Notify users of unauthorized sign-ins to their accounts +--- + +Clerk detects sign-in attempts from unrecognized devices to protect users from unauthorized access to their accounts. This security feature helps identify potentially malicious sign-in activity. + +## Email notification for unauthorized access + +When a sign-in attempt is made from an unfamiliar device, Clerk notifies the account owner by email with details about the newly created session. The email notification varies depending on the instance's configuration and the application's billing plan. + +By default, the email includes information about the unauthorized sign-in attempt, such as device type, operating system, IP address, location, and the sign-in method used. If you've set a support email for your app, Clerk will add instructions for the user to contact the app administrator. + +For supported instances, the email might also include a button that allows users to sign out from the unrecognized device. Selecting this button immediately revokes the session. + +To customize the unauthorized sign-in email notification: + +1. In the Clerk Dashboard, navigate to the [**Emails**](https://dashboard.clerk.com/last-active?path=customization/email) page. +1. Select **Sign in from new device**. You'll be redirected to the template settings page. +1. Edit the email template. +1. Select **Apply changes**. + +## Revoke sessions for unauthorized sign-ins + +> [!WARNING] +> This feature isn't available in production for free plans but can be tested for free in development mode. For more information, see the [pricing](/pricing){{ target: '_blank' }} page. + +For apps that support this feature, users can immediately revoke unauthorized sign-ins directly from the email notification. With a single click, the suspicious session is revoked and the user is redirected to a confirmation page. + +The confirmation page depends on the instance configuration: + +- [Account Portal](/docs/customization/account-portal/overview) enabled: The user is redirected to the [unauthorized sign-in](/docs/customization/account-portal/overview#unauthorized-sign-in) page, where content can be customized based on the app's theme. +- Account Portal disabled: The user sees a plain text confirmation of the successful session revocation. + +In either case, after revoking the session, users must sign in again unless they have an active session on their device. + +To customize the URL path of the unauthorized sign-in page: + +1. In the Clerk Dashboard, navigate to the [**Paths**](https://dashboard.clerk.com/last-active?path=paths) page. +1. Under **Application paths**, enter the **Unauthorized sign in URL** path. +1. Select **Save**. diff --git a/docs/telemetry.mdx b/docs/telemetry.mdx index 770a82178b..9e5dfc27ab 100644 --- a/docs/telemetry.mdx +++ b/docs/telemetry.mdx @@ -72,7 +72,7 @@ CLERK_TELEMETRY_DISABLED=1 ### `telemetry` prop -If you are using `@clerk/clerk-react` directly, or using an SDK that doesn't have environment variable support, you can opt out by passing the `telemetry` prop to ``: +If you are using `@clerk/clerk-react` directly, or using an SDK that doesn't have environment variable support, you can opt out by passing the `telemetry` prop to ``: ```tsx @@ -80,7 +80,9 @@ If you are using `@clerk/clerk-react` directly, or using an SDK that doesn't hav ### Framework specific instructions - + ```env {{ filename: '.env.local' }} NEXT_PUBLIC_CLERK_TELEMETRY_DISABLED=1 ``` @@ -109,4 +111,12 @@ If you are using `@clerk/clerk-react` directly, or using an SDK that doesn't hav ```env {{ filename: '.env.local' }} PUBLIC_CLERK_TELEMETRY_DISABLED=1 ``` + + ```env {{ filename: '.env' }} + VITE_CLERK_TELEMETRY_DISABLED=1 + ``` + + ```env {{ filename: '.env' }} + VITE_CLERK_TELEMETRY_DISABLED=1 + ``` diff --git a/docs/testing/cypress/overview.mdx b/docs/testing/cypress/overview.mdx index cf29c71c31..60c43969f2 100644 --- a/docs/testing/cypress/overview.mdx +++ b/docs/testing/cypress/overview.mdx @@ -14,7 +14,7 @@ This guide will help you set up your environment for creating Clerk-authenticate > Check out the [demo repo](https://github.com/clerk/clerk-cypress-nextjs) that tests a Clerk-powered application using [Testing Tokens](/docs/testing/overview#testing-tokens). - ### Install `@clerk/testing` + ## Install `@clerk/testing` Clerk's testing package provides integration helpers for popular testing frameworks. Run the following command to install it: @@ -32,7 +32,7 @@ This guide will help you set up your environment for creating Clerk-authenticate ``` - ### Set your API keys + ## Set your API keys In your test runner, set your Publishable and Secret Keys as the `CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY` environment variables, respectively. @@ -45,7 +45,7 @@ This guide will help you set up your environment for creating Clerk-authenticate > [!WARNING] > Ensure you provide the Secret Key in a secure manner, to avoid leaking it to third parties. For example, if you are using GitHub Actions, refer to [_Using secrets in GitHub Actions_](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions). - ### Global setup + ## Global setup To set up Clerk with Cypress, call the `clerkSetup()` function in your [`cypress.config.ts`](https://docs.cypress.io/guides/references/configuration) file. @@ -65,7 +65,7 @@ This guide will help you set up your environment for creating Clerk-authenticate `clerkSetup()` will retrieve a [Testing Token](/docs/testing/overview#testing-tokens) once the test suite starts, making it available for all subsequent tests. - ### Use Clerk Testing Tokens + ## Use Clerk Testing Tokens Now that Cypress is configured with Clerk, use the `setupClerkTestingToken()` function in your tests to integrate the Testing Token. See the following example: diff --git a/docs/testing/overview.mdx b/docs/testing/overview.mdx index e42790ca92..03e99e2955 100644 --- a/docs/testing/overview.mdx +++ b/docs/testing/overview.mdx @@ -21,7 +21,7 @@ Obtained via the [Backend API](/docs/reference/backend-api/tag/Testing-Tokens){{ Once retrieved, include the token value in the `__clerk_testing_token` query parameter in your Frontend API requests. For example, a sign-up request using a Testing Token would look like this: ```shell -POST https://happy-hippo-1.clerk.accounts.dev/v1/sign_ups?__clerk_testing_token=1713877200-c_2J2MvPu9PnXcuhbPZNao0LOXqK9A7YrnBn0HmIWxy +POST https://happy-hippo-1.clerk.accounts.dev/v1/client/sign_ups?__clerk_testing_token=1713877200-c_2J2MvPu9PnXcuhbPZNao0LOXqK9A7YrnBn0HmIWxy ``` For more information, feedback or issues, visit the [`@clerk/testing`](https://github.com/clerk/javascript/tree/main/packages/testing) package. diff --git a/docs/testing/playwright/overview.mdx b/docs/testing/playwright/overview.mdx index 045c7a409f..dfa0dff650 100644 --- a/docs/testing/playwright/overview.mdx +++ b/docs/testing/playwright/overview.mdx @@ -9,7 +9,7 @@ description: Use Playwright to write end-to-end tests with Clerk. > See the [demo repo](https://github.com/clerk/clerk-playwright-nextjs) that demonstrates testing a Clerk-powered application using [Testing Tokens](/docs/testing/overview#testing-tokens). To run the tests, you'll need dev instance Clerk API keys, a test user with username and password, and have username and password authentication enabled in the Clerk Dashboard. - ### Install `@clerk/testing` + ## Install `@clerk/testing` Clerk's testing package provides integration helpers for popular testing frameworks. Run the following command to install it: @@ -27,7 +27,7 @@ description: Use Playwright to write end-to-end tests with Clerk. ``` - ### Set your API keys + ## Set your API keys In your test runner, set your Publishable and Secret Keys as the `CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY` environment variables, respectively. @@ -39,7 +39,7 @@ description: Use Playwright to write end-to-end tests with Clerk. > [!WARNING] > Ensure that the Secret Key is provided securely to prevent exposure to third parties. For example, if you are using GitHub Actions, refer to [_Using secrets in GitHub Actions_](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions). - ### Configure Playwright with Clerk + ## Configure Playwright with Clerk The `clerkSetup()` function obtains a Testing Token when your test suite starts, making it available for all subsequent tests to use. This ensures that you don't have to manually generate a Testing Token for each test. @@ -49,6 +49,9 @@ description: Use Playwright to write end-to-end tests with Clerk. import { clerkSetup } from '@clerk/testing/playwright' import { test as setup } from '@playwright/test' + // Setup must be run serially, this is necessary if Playwright is configured to run fully parallel: https://playwright.dev/docs/test-parallel + setup.describe.configure({ mode: 'serial' }) + setup('global setup', async ({}) => { await clerkSetup() }) @@ -57,7 +60,7 @@ description: Use Playwright to write end-to-end tests with Clerk. > [!NOTE] > You can manually set the Testing Token by using the `CLERK_TESTING_TOKEN` environment variable instead of calling `clerkSetup()`. - ### Use `setupClerkTestingToken()` + ## Use `setupClerkTestingToken()` Now that Playwright is configured with Clerk, you can use the `setupClerkTestingToken()` function to include the Testing Token in individual test cases. This function injects the Testing Token for the specific test, ensuring the test can bypass Clerk's bot detection mechanisms. See the following example: diff --git a/docs/testing/playwright/test-authenticated-flows.mdx b/docs/testing/playwright/test-authenticated-flows.mdx index b3d1af2c4b..4c3054ef64 100644 --- a/docs/testing/playwright/test-authenticated-flows.mdx +++ b/docs/testing/playwright/test-authenticated-flows.mdx @@ -11,7 +11,7 @@ This guide demonstrates how to save the auth state globally and load it in your > See the [demo repo](https://github.com/clerk/clerk-playwright-nextjs) that demonstrates testing a Clerk-powered application using [Testing Tokens](/docs/testing/overview#testing-tokens). To run the tests, you'll need dev instance Clerk API keys, a test user with username and password, and have username and password authentication enabled in the Clerk Dashboard. - ### Create a storage directory + ## Create a storage directory Create a `playwright/.clerk` directory and add it to your `.gitignore`. Once the auth state is generated, it will be stored to a file in this directory. Later on, tests will reuse this state and start already authenticated. @@ -20,7 +20,7 @@ This guide demonstrates how to save the auth state globally and load it in your echo $'\nplaywright/.clerk' >> .gitignore ``` - ### Prepare auth state for your tests + ## Prepare auth state for your tests Authenticate and save the auth state in your [global setup file](https://playwright.dev/docs/test-global-setup-teardown). @@ -66,11 +66,11 @@ This guide demonstrates how to save the auth state globally and load it in your }) ``` - ### Load the stored auth state in your tests + ## Load the stored auth state in your tests You can either load the stored auth state [in the config](#-in-the-config) or directly [in a test file](#-in-a-test-file). Loading in the config is useful if you want to authenticate once and reuse the same auth state for all tests or groups of tests. Loading in a test file is useful if you want to authenticate for a specific test case. - #### In the config + ### In the config In your `playwright.config.ts`, create a `global setup` project and declare it as a [dependency](https://playwright.dev/docs/test-projects#dependencies) for all your testing projects. This means that the `global setup` project will always run before all the tests, and because it's where you prepared auth state, it will authenticate before all the tests. All testing projects should use the authenticated state as `storageState`. @@ -103,7 +103,7 @@ This guide demonstrates how to save the auth state globally and load it in your ] ``` - #### In a test file + ### In a test file To use the stored auth state in a test file, see the following example: diff --git a/docs/troubleshooting/create-a-minimal-reproduction.mdx b/docs/troubleshooting/create-a-minimal-reproduction.mdx index e6865777ae..7018ee20f3 100644 --- a/docs/troubleshooting/create-a-minimal-reproduction.mdx +++ b/docs/troubleshooting/create-a-minimal-reproduction.mdx @@ -19,9 +19,11 @@ The best way to create a minimal reproduction is to start fresh, with a minimal - [Vanilla JS](https://github.com/clerkinc/clerk-js-starter) - [Expo](https://github.com/clerkinc/clerk-expo-starter) - [Remix](https://github.com/clerk/clerk-remix-v2) +- [React Router](https://github.com/clerk/clerk-react-router-quickstart) - [Redwood](https://github.com/clerkinc/clerk-redwood-starter) - [Rails](https://github.com/clerkinc/clerk-rails-starter) - [Chrome Extension](https://github.com/clerkinc/clerk-chrome-extension-starter) +- [Tanstack Start](https://github.com/clerk/clerk-tanstack-start-quickstart) ## Steps to create a minimal reproduction diff --git a/docs/upgrade-guides/api-keys.mdx b/docs/upgrade-guides/api-keys.mdx deleted file mode 100644 index 67bb9cb24a..0000000000 --- a/docs/upgrade-guides/api-keys.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Publishable and Secret Keys -description: Dive into Clerk's latest V3 update. ---- - -> [!NOTE] -> If your application was created after January 18, 2023, you're already using Publishable and Secret Keys. - -In early Clerk SDKs, developers were required to configure three keys: - -- Frontend API URL -- API key -- JWT key (depending on the SDK version) - -New SDKs have replaced these with two keys: - -- Publishable Key (prefixed with `pk_test_` or `pk_live_`) -- Secret Key (prefixed with `sk_test_` or `sk_live_`) - -The name and format of these keys are common among developer tools, and we adopted them to provide a more familiar developer experience. - -Although legacy keys will remain operational, we have updated our documentation and code samples to use the new Publishable Key and Secret Key format. - -> [!CAUTION] -> Legacy keys cannot be mixed with the new Publishable and Secret Keys. It is important that you replace all keys at once. - -We recommend updating at your earliest convenience. diff --git a/docs/users/metadata.mdx b/docs/users/metadata.mdx index ae75fd30b8..a962fe534a 100644 --- a/docs/users/metadata.mdx +++ b/docs/users/metadata.mdx @@ -18,7 +18,7 @@ Metadata allows for custom data to be saved on the [`User` object](/docs/users/o Private metadata is only accessible by the backend, which makes this useful for storing sensitive data that you don't want to expose to the frontend. For example, you could store a user's Stripe customer ID. -### Setting private metadata +### Set private metadata @@ -109,9 +109,9 @@ Private metadata is only accessible by the backend, which makes this useful for -### Retrieving private metadata +### Retrieve private metadata -You can retrieve the private metadata for a user by using the [`getUser`](/docs/references/backend/user/get-user) method. This method will return the `User` object which contains the private metadata. +You can retrieve the private metadata for a user by using the JavaScript Backend SDK's [`getUser()`](/docs/references/backend/user/get-user) method. This method will return the `User` object which contains the private metadata. @@ -184,7 +184,7 @@ You can retrieve the private metadata for a user by using the [`getUser`](/docs/ Public metadata is accessible by both the frontend and the backend, but can only be set on the backend. This is useful for storing data that you want to expose to the frontend, but don't want the user to be able to modify. For example, you could store a custom role for a user. -### Setting public metadata +### Set public metadata @@ -198,7 +198,7 @@ Public metadata is accessible by both the frontend and the backend, but can only const client = await clerkClient() await client.users.updateUserMetadata(userId, { - privateMetadata: { + publicMetadata: { stripeId: stripeId, }, }) @@ -275,25 +275,25 @@ Public metadata is accessible by both the frontend and the backend, but can only -### Retrieving public metadata +### Retrieve public metadata -There are multiple ways to retrieve public metadata. It is available on the `User` object returned by the [`useUser`](/docs/references/react/use-user) hook, and it can also be attached to the session token to be retrieved with [`auth()`](/docs/references/nextjs/auth) and [`useAuth()`](/docs/references/react/use-auth). If you need to retrieve public metadata frequently in the backend, the best option is to attach it to the session token and retrieve it from the session token. +There are multiple ways to retrieve public metadata. -To read about customizing your session token and retrieving that data, check out our [session token customization guide](/docs/backend-requests/making/custom-session-token). +On the frontend, it's available on the [`User`](/docs/references/javascript/user/user) object which can be accessed using the [`useUser()`](/docs/references/react/use-user) hook. -## Unsafe metadata +On the backend, it's available on the [Backend `User`](/docs/references/backend/types/backend-user) object which can be accessed using the JavaScript Backend SDK's [`getUser()`](/docs/references/backend/user/get-user) method. It can also be attached to a session token, and the `sessionClaims` of the session token can be retrieved on the [`Auth`](/docs/references/nextjs/auth-object) object. If you need to retrieve public metadata frequently in the backend, the best option is to attach it to the session token and retrieve it from the session token. See the [guide on customizing your session token](/docs/backend-requests/making/custom-session-token). -If you need to implement custom fields that will be attached to the `User` object from the frontend (using our ClerkJS library or the [Frontend API](/docs/reference/frontend-api){{ target: '_blank' }}), you should choose the `unsafeMetadata` property. +## Unsafe metadata -One common use case for this attribute is to implement custom fields that will be attached to the `User` object. +Unsafe metadata can be both read and set from the frontend and the backend. It's called "unsafe" metadata because it can be modified directly from the frontend, which means malicious users could potentially tamper with these values. -Clerk has named this type of metadata "unsafe" since it can be set and accessed by both the Frontend API and the Backend API. This provides a quick method to add custom attributes to a user. These attributes will be stored on the `User` object and will be available for access at all times. +Unsafe metadata is the only metadata property that can be set during sign-up, so a common use case is to use it in [custom onboarding flows](/docs/guides/add-onboarding-flow). Custom data collected during the onboarding (sign-up) flow can be stored in the [`SignUp`](/docs/references/javascript/sign-up/sign-up) object. After a successful sign-up, `SignUp.unsafeMetadata` is copied to the `User` object as `User.unsafeMetadata`. From that point on, the unsafe metadata is accessible as a direct attribute of the `User` object. -The "unsafe" custom attributes can be set upon sign-up when creating or updating a [`SignUp`](/docs/references/javascript/sign-up/sign-up) object. After a successful sign-up, these attributes will be copied to the `User` object. From that point on they can be accessed as a direct attribute of the `User` object. +### Set unsafe metadata -### Setting unsafe metadata +The following examples demonstrate how to update unsafe metadata for an existing user. Updating `unsafeMetadata` replaces the previous value; it doesn't perform a merge. To merge data, you can pass a combined object such as `{ …user.unsafeMetadata, …newData }` to the `unsafeMetadata` parameter. -Updating this value overrides the previous value; it does not merge. To perform a merge, you can pass something like `{ …user.unsafeMetadata, …newData }` to this parameter. +The following examples demonstrate how to update `unsafeMetadata` using [the Backend API](#using-the-backend-api) or [the Frontend SDKs](#using-the-frontend-sdks). #### Using the Backend API @@ -361,7 +361,6 @@ Updating this value overrides the previous value; it does not merge. To perform ```ruby {{ filename: 'private.rb' }} - # ruby json example with a private metadata and stripe id require 'clerk' require 'json' @@ -370,7 +369,7 @@ Updating this value overrides the previous value; it does not merge. To perform } clerk = Clerk::SDK.new(api_key: "your_clerk_secret_key") - clerk.users.updateMetadata("user_xyz", unsafe_metadata: unsafeMetadata) + clerk.users.updateMetadata("user_123", unsafe_metadata: unsafeMetadata) ``` @@ -507,8 +506,10 @@ Updating this value overrides the previous value; it does not merge. To perform -### Retrieving unsafe metadata +### Retrieve unsafe metadata + +There are multiple ways to retrieve unsafe metadata. -There are multiple ways to retrieve unsafe metadata. It is available in the `User` object returned by the [`useUser()`](/docs/references/react/use-user) hook. It can also be attached to a session token, which can be retrieved with the [`auth()`](/docs/references/nextjs/auth) helper in Next.js applications, or with the [`useAuth()`](/docs/references/react/use-auth) hook. If you need to retrieve unsafe metadata frequently in the backend, the best option is to attach it to the session token and retrieve it from the session token. +On the frontend, it is available on the [`User`](/docs/references/javascript/user/user) object, which you can access by using the [`useUser()`](/docs/references/react/use-user) hook. -To read about customization your session token and retrieving that data, check out our [session token customization guide](/docs/backend-requests/making/custom-session-token). +On the backend, it's available on the [Backend `User`](/docs/references/backend/types/backend-user) object which can be accessed using the JavaScript Backend SDK's [`getUser()`](/docs/references/backend/user/get-user) method. It can also be attached to a session token, and the `sessionClaims` of the session token can be retrieved on the [`Auth`](/docs/references/nextjs/auth-object) object. If you need to retrieve unsafe metadata frequently in the backend, the best option is to attach it to the session token and retrieve it from the session token. See the [guide on customizing your session token](/docs/backend-requests/making/custom-session-token). diff --git a/docs/users/user-impersonation.mdx b/docs/users/user-impersonation.mdx index d0fce1c35a..c41c9e76ea 100644 --- a/docs/users/user-impersonation.mdx +++ b/docs/users/user-impersonation.mdx @@ -3,7 +3,7 @@ title: User impersonation description: Clerk's user impersonation feature allows you to sign in as different users to offer customer support or debug issues. --- -User impersonation is a way to offer customer support by logging into your application from their accounts. Doing so enables you to directly reproduce and remedy any issues they're experiencing. +Clerk's user impersonation feature allows you to sign in to your application as one of your users, enabling you to directly reproduce and remedy any issues they're experiencing. It's a helpful feature for customer support and debugging. ## Impersonate a user diff --git a/docs/users/web3.mdx b/docs/users/web3.mdx index cb5f89563b..a823fee5ae 100644 --- a/docs/users/web3.mdx +++ b/docs/users/web3.mdx @@ -7,9 +7,9 @@ Learn how to use Clerk to quickly and easily add secure authentication and user ## Before you start -You need to create a Clerk application in the [Clerk Dashboard](https://dashboard.clerk.com/) and configure the application to use **Sign in with Metamask** or **Sign in with Coinbase Wallet**. For more information on how to set up a Clerk application, see the [setup guide](/docs/quickstarts/setup-clerk). To enable Metamask or Coinbase Wallet authentication, see the [dedicated guide](/docs/authentication/configuration/sign-up-sign-in-options#web3-authentication). +You need to create a Clerk application in the [Clerk Dashboard](https://dashboard.clerk.com/) and configure the application to use **Sign in with Metamask**, **Sign in with Coinbase Wallet** or **Sign in with OKX Wallet**. For more information on how to set up a Clerk application, see the [setup guide](/docs/quickstarts/setup-clerk). To enable Metamask, Coinbase Wallet, or OKX Wallet authentication, see the [dedicated guide](/docs/authentication/configuration/sign-up-sign-in-options#web3-authentication). -Ensure that you have downloaded the [Metamask](https://metamask.io/download/) or [Coinbase Wallet](https://www.coinbase.com/wallet/downloads) plugins and installed it on your browser to ensure a seamless sign-in flow. +Ensure that you've installed the [Metamask](https://metamask.io/download/), [Coinbase Wallet](https://www.coinbase.com/wallet/downloads), or [OKX Wallet](https://www.okx.com/help/section/faq-web3-wallet) plugins for a seamless sign-in experience. ## Creating a new Next.js app @@ -17,9 +17,9 @@ Once you have a Clerk application set up in the dashboard, it's time to create a ## Accessing the Web3 address from the frontend -At this point, you should have a Next.js application integrated with Clerk and with Metamask or Coinbase Wallet authentication enabled. Run `npm run dev` and visit `localhost:3000`. If you followed the guide, all of the pages to your application should be protected, and you should see your sign-in page. +At this point, your Next.js application should be integrated with Clerk and configured for authentication using Metamask, Coinbase Wallet, or OKX Wallet. Run `npm run dev` and visit `localhost:3000`. If you followed the guide, all pages in your application will be protected, and you should see your sign-in page. -After signing in with Metamask or Coinbase Wallet, you'll be presented with the Next.js default start screen. Let's modify the start screen to display a user's primary Web3 address on the page. +After signing in with your Web3 provider, you'll be presented with the Next.js default start screen. Let's modify the start screen to display a user's primary Web3 address on the page. In this example, the [`User`](/docs/references/javascript/user/user) object for the current user can be accessed through the [`useUser()`](/docs/references/react/use-user) hook. The user's primary Web3 address can then be retrieved from the `User` object. diff --git a/docs/webhooks/loops.mdx b/docs/webhooks/loops.mdx index eae8cb1dc3..73bffcb29f 100644 --- a/docs/webhooks/loops.mdx +++ b/docs/webhooks/loops.mdx @@ -25,7 +25,7 @@ description: Learn how to add your Clerk users to your Loops audience, and send This tutorial demonstrates how to sync your Clerk users to Loops so you can email users with Loop's email marketing tools. You will also learn how to send email sequences to new Clerk users. - ### Create a Clerk webhook endpoint in Loops + ## Create a Clerk webhook endpoint in Loops Loops' [Incoming webhooks](https://loops.so/docs/integrations/incoming-webhooks) feature lets Loops accept webhooks directly from external platforms like Clerk. @@ -34,7 +34,7 @@ This tutorial demonstrates how to sync your Clerk users to Loops so you can emai 1. Navigate to the **Clerk** settings page in the [Loops dashboard](https://app.loops.so/settings?page=clerk). 1. Save the **Endpoint URL** somewhere secure; you're going to need it for Clerk's webhook configuration. - ### Create a webhook in the Clerk Dashboard + ## Create a webhook in the Clerk Dashboard You must create a new Clerk webhook endpoint so that it can send data to Loops. Here is where you will provide the **Endpoint URL** from the last step, and then choose the events you want to listen to. @@ -45,14 +45,14 @@ This tutorial demonstrates how to sync your Clerk users to Loops so you can emai 1. Select the **Create** button. 1. You will be redirected to your endpoint's settings page. Leave this page open. - ### Add your signing secret in Loops + ## Add your signing secret in Loops To keep communication secure between the two platforms: 1. On the Clerk endpoint's settings page, copy the **Signing Secret**. It should be on the right side of the page with an eye icon next to it. 1. Back in the Loops dashboard, add the **Signing Secret**. - ### Configure Loops events + ## Configure Loops events The final step is to configure which events Loops should accept from Clerk and what Loops should do with the data. diff --git a/docs/webhooks/sync-data.mdx b/docs/webhooks/sync-data.mdx index 7f6267e2c5..a7024f6bf3 100644 --- a/docs/webhooks/sync-data.mdx +++ b/docs/webhooks/sync-data.mdx @@ -39,7 +39,7 @@ Clerk offers many events, but three key events include: These steps apply to any Clerk event. To make the setup process easier, it's recommended to keep two browser tabs open: one for your Clerk [**Webhooks**](https://dashboard.clerk.com/last-active?path=webhooks) page and one for your [ngrok dashboard](https://dashboard.ngrok.com). - ### Set up ngrok + ## Set up ngrok To test a webhook locally, you need to expose your local server to the internet. This guide uses [ngrok](https://ngrok.com/) which creates a **forwarding URL** that sends the webhook payload to your local server. @@ -51,7 +51,7 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec 1. Paste the command in your terminal and change the port number to match your server's port. For this guide, replace `80` with `3000`, then run the command in your terminal. It will generate a **Forwarding** URL. It should resemble `https://fawn-two-nominally.ngrok-free.app`. 1. Save your **Forwarding** URL somewhere secure. Close the panel. - ### Set up a webhook endpoint + ## Set up a webhook endpoint 1. In the Clerk Dashboard, navigate to the [**Webhooks**](https://dashboard.clerk.com/last-active?path=webhooks) page. 1. Select **Add Endpoint**. @@ -59,7 +59,7 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec 1. In the **Subscribe to events** section, scroll down and select `user.created`. 1. Select **Create**. You'll be redirected to your endpoint's settings page. Keep this page open. - ### Add your Signing Secret to `.env.local` + ## Add your Signing Secret to `.env.local` To verify the webhook payload, you'll need your endpoint's **Signing Secret**. Since you don't want this secret exposed in your codebase, store it as an environment variable in your `.env.local` file during local development. @@ -72,11 +72,11 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec SIGNING_SECRET=whsec_123 ``` - ### Set the webhook route as public in your Middleware + ## Set the webhook route as public in your Middleware Incoming webhook events don't contain auth information. They come from an external source and aren't signed in or out, so the route must be public to allow access. If you're using `clerkMiddleware()`, ensure that the `/api/webhooks(.*)` route is set as public. For information on configuring routes, see the [`clerkMiddleware()` guide](/docs/references/nextjs/clerk-middleware). - ### Install `svix` + ## Install `svix` Clerk uses [`svix`](https://www.npmjs.com/package/svix) to deliver webhooks, so you'll use it to verify the webhook signature. Run the following command in your terminal to install the package: @@ -94,7 +94,7 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec ``` - ### Create the endpoint + ## Create the endpoint Set up a Route Handler that uses `svix` to verify the incoming Clerk webhook and process the payload. @@ -239,7 +239,7 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec
- ### Narrow to a webhook event for type inference + ## Narrow to a webhook event for type inference `WebhookEvent` encompasses all possible webhook types. Narrow down the event type for accurate typing for specific events. @@ -265,7 +265,7 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec - `SMSMessageJSON` - `UserJSON` - ### Test the webhook + ## Test the webhook 1. Start your Next.js server. 1. In your endpoint's settings page in the Clerk Dashboard, select the **Testing** tab. @@ -273,14 +273,14 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec 1. Select **Send Example**. 1. In the **Message Attempts** section, confirm that the event is labeled with `Succeeded`. - #### Handling failed messages + ### Handling failed messages 1. In the **Message Attempts** section, select the event labeled with `Failed`. 1. Scroll down to the **Webhook Attempts** section. 1. Toggle the arrow next to the **Status** column. 1. Review the error. Solutions vary by error type. For more information, refer to the [Debug your webhooks](/docs/webhooks/debug-your-webhooks) guide. - ### Trigger the webhook + ## Trigger the webhook To trigger the `user.created` event, you can do either one of the following: @@ -290,7 +290,7 @@ These steps apply to any Clerk event. To make the setup process easier, it's rec You should be able to see the webhook's payload logged to your terminal. You can also check the Clerk Dashboard to see the webhook attempt, the same way you did when [testing the webhook](#test-the-webhook).
-### Configure your production instance +## Configure your production instance 1. When you're ready to deploy your app to production, follow [the guide on deploying your Clerk app to production](/docs/deployments/overview). 1. Create your production webhook by following the steps in the previous [Set up a webhook endpoint](#set-up-a-webhook-endpoint) section. In the **Endpoint URL** field, instead of pasting the ngrok URL, paste your production app URL. diff --git a/public/images/account-portal/unauthorized-sign-in.png b/public/images/account-portal/unauthorized-sign-in.png new file mode 100644 index 0000000000..456dd2c0ae Binary files /dev/null and b/public/images/account-portal/unauthorized-sign-in.png differ diff --git a/styleguides/SSO.STYLEGUIDE.MD b/styleguides/SSO.STYLEGUIDE.MD index d5dd940c85..24bd4998dd 100644 --- a/styleguides/SSO.STYLEGUIDE.MD +++ b/styleguides/SSO.STYLEGUIDE.MD @@ -38,7 +38,7 @@ These are the guidelines we use to write our SSO guides. - The `Test your OAuth` section should be included in the `` and formatted as follows: ```mdx - ### Test your OAuth + ## Test your OAuth The simplest way to test your OAuth is to visit your Clerk app's [Account Portal](/docs/customization/account-portal/overview), which is available for all Clerk apps out-of-the-box. diff --git a/styleguides/STYLEGUIDE.md b/styleguides/STYLEGUIDE.md index 4a6de61262..83c03cdbba 100644 --- a/styleguides/STYLEGUIDE.md +++ b/styleguides/STYLEGUIDE.md @@ -397,7 +397,7 @@ Component references should be wrapped in `< />` if they are self closing. Other The last case is incorrect because the `` component will never wrap children, and therefore, should have a self-closing tag. -> Use the `` component. +> Use the `` component. The last case is incorrect because the `` component will always wrap children and will never be self-closing.