@@ -152,6 +152,27 @@ The [`Auth`](/docs/reference/backend/types/auth-object) object is a server-side
```
+
+ The Astro SDK provides the `locals.auth()` function to access the `Auth` object. [Learn more about using `locals.auth()`](/docs/astro/guides/users/reading#server-side).
+
+ ```astro {{ filename: 'src/pages/example.astro' }}
+ ---
+ // Use `locals.auth()` to access the `Auth` object
+ const { actor, userId } = Astro.locals.auth()
+ ---
+
+
+ {
+ actor && (
+
+ user {actor.sub} has signed in as user {userId || ''}
+
+ )
+ }
+
+ ```
+
+
The Express SDK provides a [middleware](/docs/reference/express/overview#clerk-middleware) that attaches the [`Auth`](/docs/reference/backend/types/auth-object) object to the `request` object.
@@ -175,4 +196,59 @@ The [`Auth`](/docs/reference/backend/types/auth-object) object is a server-side
})
```
+
+
+ The React Router SDK provides the [`getAuth()`](/docs/reference/react-router/get-auth) function to access the `Auth` object.
+
+ ```tsx {{ filename: 'app/routes/example.tsx' }}
+ import { redirect } from 'react-router'
+ import { clerkClient, getAuth } from '@clerk/react-router/server'
+ import type { Route } from './+types/example'
+
+ export async function loader(args: Route.LoaderArgs) {
+ // Use `getAuth()` to access the `Auth` object
+ const { isAuthenticated, actor, userId } = await getAuth(args)
+
+ return {
+ actor: actor,
+ userId: userId || '',
+ }
+ }
+
+ export default function Example({ loaderData }: Route.ComponentProps) {
+ return (
+
+ {loaderData.actor && (
+
+ user {loaderData.actor.sub} has signed in as user {loaderData.userId}
+
+ )}
+
+ )
+ }
+ ```
+
+
+
+ The Tanstack React Start SDK provides the `auth()` function to access the `Auth` object. [Learn more about using `auth()`](/docs/tanstack-react-start/guides/users/reading#server-side).
+
+ ```tsx {{ filename: 'src/routes/api/example.tsx' }}
+ import { auth } from '@clerk/tanstack-react-start/server'
+ import { json } from '@tanstack/react-start'
+ import { createFileRoute } from '@tanstack/react-router'
+
+ export const ServerRoute = createFileRoute('/api/example')({
+ server: {
+ handlers: {
+ GET: async () => {
+ // Use `auth()` to access the `Auth` object
+ const { actor, userId } = await auth()
+
+ return json({ actor, userId })
+ },
+ },
+ },
+ })
+ ```
+
diff --git a/docs/guides/users/inviting.mdx b/docs/guides/users/inviting.mdx
index 4629e9aa21..13426a4f44 100644
--- a/docs/guides/users/inviting.mdx
+++ b/docs/guides/users/inviting.mdx
@@ -5,7 +5,7 @@ description: Learn how to invite users to your Clerk application.
Inviting users to your Clerk application allows you to onboard new users seamlessly by sending them a unique invitation link.
-Once you create an invitation, Clerk sends an email to the invited user with a unique invitation link. When the user visits the invitation link, they will be redirected to the [Account Portal sign-up page](/docs/guides/customizing-clerk/account-portal#sign-up) and **their email address will be automatically verified.** If you want to redirect the user to a specific page in your application, you can [specify a redirect URL when creating the invitation](#redirect-url).
+Once you create an invitation, Clerk sends an email to the invited user with a unique invitation link. When the user visits the invitation link, they will be redirected to the [Account Portal sign-up page](/docs/guides/customizing-clerk/account-portal#sign-up) and **their email address will be automatically verified.** If you want to redirect the user to a specific page in your application, you can [specify a redirect URL when creating the invitation](#with-a-redirect-url).
Invitations expire after a month. If the user clicks on an expired invitation, they will get redirected to the application's sign-up page and will have to go through the normal sign-up flow. Their email address will not be auto-verified.
@@ -14,122 +14,57 @@ Invitations expire after a month. If the user clicks on an expired invitation, t
## Create an invitation
-You can create an invitation in the [Clerk Dashboard](#using-clerk-dashboard) or [using the Backend API](#using-backend-api).
+You can create an invitation either in the [Clerk Dashboard](#in-the-clerk-dashboard) or [programmatically](#programmatically). When making this decision, keep in mind that if you create an invitation through the Clerk Dashboard, you can only set an invitation expiration date. If you create an invitation programatically, you are able to set more options, such as the URL you want the user to be redirected to after they accept the invitation, metadata to add to the invitation, or whether an invitation should be created if there is already an existing invitation for the given email address.
-### Using Clerk Dashboard
+### In the Clerk Dashboard
-To invite users, navigate to the **Users** page from the top-level menu, then select the **Invitations** tab. Select **Invite user** and enter the email address of the person you want to invite. Optionally, set an expiration date for the invitation. Once you've entered the necessary details, select **Send invite** to send the invitation email.
+To create an invitation in the Clerk Dashboard, navigate to the [**Invitations**](https://dashboard.clerk.com/~/users/invitations) page.
-> [!TIP]
-> The same page will be available through the top-level menu, when you are in the **Restricted** sign-up mode.
-
-### Using Backend API
-
-You can either use a cURL command or the [JS Backend SDK](/docs/js-backend/getting-started/quickstart) to create an invitation. Clerk's JS Backend SDK is a wrapper around the Backend API that makes it easier to interact with the API. Use the following tabs to see examples for each method.
-
-
-
- The following example demonstrates how to create an invitation using cURL.
-
-
- Replace the email address with the email address you want to invite. Your Clerk Secret Key is already injected into the code snippet.
-
-
-
- Replace the email address with the email address you want to invite. Update `YOUR_SECRET_KEY` with your Clerk Secret Key which can be found on the [**API keys**](https://dashboard.clerk.com/~/api-keys) page in the Clerk Dashboard.
-
+### Programmatically
- ```bash {{ filename: 'terminal' }}
- curl https://api.clerk.com/v1/invitations -X POST -d '{"email_address": "email@example.com"}' -H "Authorization:Bearer {{secret}}" -H 'Content-Type:application/json'
- ```
-
+To create an invitation programmatically, you can either [make a request directly to Clerk's Backend API](/docs/reference/backend/invitations/create-invitation#backend-api-bapi-endpoint) or use the [`createInvitation()`](/docs/reference/backend/invitations/create-invitation) method as shown in the following example.
-
- To use the JS Backend SDK to create an invitation, see the [`createInvitation()` reference](/docs/reference/backend/invitations/create-invitation).
-
-
+
See the [Backend API reference](/docs/reference/backend-api/tag/invitations/post/invitations){{ target: '_blank' }} for an example of the response.
-### Redirect URL
+### With a redirect URL
-When you create an invitation, you can specify a `redirect_url` parameter. This parameter tells Clerk where to redirect the user when they visit the invitation link.
-
-The following example demonstrates how to use cURL to create an invitation with the `redirect_url` set to `https://www.example.com/accept-invitation`:
+> [!WARNING]
+> You currently cannot specify a redirect URL when creating an invitation in the Clerk Dashboard; if you need to specify a redirect URL, you need to create the invitation programmatically.
-```bash
-curl https://api.clerk.com/v1/invitations -X POST -d '{"email_address": "email@example.com", "redirect_url": "https://www.example.com/accept-invitation"}' -H "Authorization:Bearer {{secret}}" -H 'Content-Type:application/json'
-```
+When you create an invitation programmatically, you can specify a `redirectUrl` parameter. This parameter tells Clerk where to redirect the user when they visit the invitation link.
-Once the user visits the invitation link, they will be redirected to the page you specified, which means you must handle the sign-up flow in your code for that page. You can either embed the [`
`](/docs/reference/components/authentication/sign-up) component on that page, or if the prebuilt component doesn't meet your specific needs or if you require more control over the logic, you can build a [custom flow](/docs/guides/development/custom-flows/authentication/application-invitations).
+Once the user visits the invitation link, they will be redirected to the page you specified, which means **you must handle the sign-up flow in your code for that page**. You can either embed the [`
`](/docs/reference/components/authentication/sign-up) component on that page, or if the prebuilt component doesn't meet your specific needs or if you require more control over the logic, you can build a [custom flow](/docs/guides/development/custom-flows/authentication/application-invitations).
> [!TIP]
>
> - To test redirect URLs in your development environment, pass your port (e.g. `http://localhost:3000`).
> - To use the Account Portal, pass the URL provided by Clerk on the [**Account Portal**](https://dashboard.clerk.com/~/account-portal) page in the Clerk Dashboard. For example, `https://prepared-phoenix-98.accounts.dev/sign-up` redirects the user to the Account Portal sign-up page.
-### Invitation metadata
-
-You can also add metadata to an invitation. Once the invited user signs up using the invitation link, the invitation metadata will end up in the user's `public_metadata`. You can find more information about user metadata in the [metadata](/docs/guides/users/extending) docs.
-
-To add metadata to an invitation, you can use the `public_metadata` property when the invitation is created.
-
-The following example demonstrates how to create an invitation with metadata using cURL.
-
-
- Replace the email address with the email address you want to invite, and the `public_metadata` with the metadata you want to add. Your Secret Key is already injected into the code snippet.
-
+### With invitation metadata
-
- Replace the email address with the email address you want to invite, and the `public_metadata` with the metadata you want to add. Update `YOUR_SECRET_KEY` with your Clerk Secret Key which can be found on the [**API keys**](https://dashboard.clerk.com/~/api-keys) page in the Clerk Dashboard.
-
+When you create an invitation programmatically, you can specify a `publicMetadata` parameter to add metadata to an invitation. Once the invited user signs up using the invitation link, the invitation metadata will end up in the user's public metadata. [Learn more about user metadata](/docs/guides/users/extending).
-```bash
-curl https://api.clerk.com/v1/invitations -X POST -d '{"email_address": "email@example.com", "public_metadata": {"age": "21"}}' -H "Authorization:Bearer {{secret}}" -H 'Content-Type:application/json'
-```
+## Revoke an invitation
-## Revoking invitations
+You can revoke an invitation at any time. Revoking an invitation prevents the user from using the invitation link that was sent to them. You can revoke an invitation in the [Clerk Dashboard](#in-the-clerk-dashboard-2) or [programmatically](#programmatically-2).
-You can revoke an invitation at any time. Revoking an invitation prevents the user from using the invitation link that was sent to them. You can revoke an invitation in the [Clerk Dashboard](#using-clerk-dashboard-2) or [using the Backend API](#using-backend-api-2).
-
-### Using Clerk Dashboard
-
-To revoke an invitation, navigate to the **Users** page from the top-level menu, then select the **Invitations** tab. Find the invitation you want to revoke and select **Revoke** from the dropdown menu on the right.
-
-> [!TIP]
-> The same page will be available through the top-level menu, when you are in the **Restricted** sign-up mode.
-
-### Using Backend API
-
-You can either use a cURL command or the [JS Backend SDK](/docs/js-backend/getting-started/quickstart) to revoke an invitation. Use the following tabs to see examples for each method.
+> [!WARNING]
+> Revoking an invitation does **not** prevent the user from signing up on their own. If you're looking to restrict access to invited users only, refer to the [**Restricted** sign-up mode](/docs/guides/secure/restricting-access#sign-up-modes).
-
-
- The following example demonstrates how to revoke an invitation using cURL.
+### In the Clerk Dashboard
-
- Replace the `` with the ID of the invitation you want to revoke. Your Secret Key is already injected into the code snippet.
-
+To revoke an invitation in the Clerk Dashboard, navigate to the [**Invitations**](https://dashboard.clerk.com/~/users/invitations) page.
-
- Replace the `` with the ID of the invitation you want to revoke and replace `YOUR_SECRET_KEY` with your Clerk Secret Key. You can find your Secret Key on the [**API keys**](https://dashboard.clerk.com/~/api-keys) page in the Clerk Dashboard.
-
+### Programmatically
- ```bash {{ filename: 'terminal' }}
- curl https://api.clerk.com/v1/invitations//revoke -X POST -H "Authorization:Bearer {{secret}}" -H 'Content-Type:application/json'
- ```
-
+To revoke an invitation programmatically, you can either [make a request directly to Clerk's Backend API](/docs/reference/backend/invitations/revoke-invitation#backend-api-bapi-endpoint) or use the [`revokeInvitation()`](/docs/reference/backend/invitations/revoke-invitation) method as shown in the following example.
-
- To use the JS Backend SDK to revoke an invitation, see the [`revokeInvitation()`](/docs/reference/backend/invitations/revoke-invitation) reference documentation.
-
-
+
See the [Backend API reference](/docs/reference/backend-api/tag/invitations/post/invitations/\{invitation_id}/revoke){{ target: '_blank' }} for an example of the response.
-> [!WARNING]
-> Revoking an invitation does **not** prevent the user from signing up on their own. If you're looking to restrict access to invited users only, refer to the [**Restricted** sign-up mode](/docs/guides/secure/restricting-access#sign-up-modes).
-
## Custom flow
Clerk's [prebuilt components](/docs/reference/components/overview) and [Account Portal pages](/docs/guides/customizing-clerk/account-portal) handle the sign-up flow for you, including the invitation flow. If Clerk's prebuilt components don't meet your specific needs or if you require more control over the logic, you can rebuild the existing Clerk flows using the Clerk API. For more information, see the [custom flow for application invitations](/docs/guides/development/custom-flows/authentication/application-invitations).
diff --git a/docs/guides/users/managing.mdx b/docs/guides/users/managing.mdx
index 08411300bf..e817f5365d 100644
--- a/docs/guides/users/managing.mdx
+++ b/docs/guides/users/managing.mdx
@@ -11,15 +11,15 @@ For more information on the `User` object, such as helper methods for retrieving
## Manage users
-You can manage your users [in the Clerk Dashboard](#in-the-clerk-dashboard), or [in your app](#in-your-app).
+You can manage your users [in the Clerk Dashboard](#in-the-clerk-dashboard), or [programmatically](#programmatically).
### In the Clerk Dashboard
To manage users in the Clerk Dashboard, navigate to the [**Users**](https://dashboard.clerk.com/~/users) page.
-### In your app
+### Programmatically
-You can manage users in your app either through the [frontend](#in-the-frontend) or [backend](#in-the-backend).
+You can manage users programmatically through the [frontend](#in-the-frontend) or [backend](#in-the-backend).
#### In the frontend
@@ -31,165 +31,32 @@ Depending on the level of abstraction you need, you can manage users in the fron
#### In the backend
-The [JS Backend SDK](/docs/js-backend/getting-started/quickstart) exposes the [Backend API](/docs/reference/backend-api){{ target: '_blank' }} resources and low-level authentication utilities for JavaScript environments.
-
-There are many operations available for managing users, such as `getUser()`, `createUser()`, and `deleteUser()`. For more information, see the [JS Backend reference docs](/docs/js-backend/getting-started/quickstart).
+The [JS Backend SDK](/docs/js-backend/getting-started/quickstart) is a wrapper around the [Backend API](/docs/reference/backend-api){{ target: '_blank' }} that makes it easier to interact with the API. It includes many methods for managing users, such as `getUser()`, `createUser()`, and `deleteUser()`. For more information, see the [JS Backend SDK reference docs](/docs/js-backend/getting-started/quickstart).
## Create users
-There are two ways to create users in Clerk: [in the Clerk Dashboard](#in-the-clerk-dashboard) or [using the Backend API](#using-the-backend-api).
-
-### In the Clerk Dashboard
-
-To create users in the Clerk Dashboard:
-
-1. In the top in the Clerk Dashboard, select [**Users**](https://dashboard.clerk.com/~/users).
-1. Select **Create user**.
-1. Enter the required user details and select **Create**.
-
-### Using the Backend API
-
-You can create users in your app using Clerk's Backend API.
-
-Use the following tabs to see examples of how to create users using one of the following:
-
-- JS Backend SDK
-- Express
-- cURL
-
-
-
- The following example shows how to create a user using the JS Backend SDK's [`createUser()`](/docs/reference/backend/user/create-user) method from the `users` sub-api of the `clerkClient` instance.
-
-
-
- ```ts {{ filename: 'route.ts' }}
- export async function POST() {
- try {
- const user = await clerkClient.users.createUser({
- emailAddress: ['test@example.com'],
- password: 'password',
- })
- return Response.json({ message: 'User created', user })
- } catch (error) {
- console.log(error)
- return Response.json({ error: 'Error creating user' })
- }
- }
- ```
-
-
- If you're using Next.js, you must `await` the instantiation of the `clerkClient` instance, like so:
-
- ```ts
- const client = await clerkClient()
-
- const response = await client.users.createUser()
- ```
-
-
-
-
- ```ts {{ filename: 'create-user.ts' }}
- import { clerkClient } from '@clerk/express'
-
- app.post('/createUser', async (req, res) => {
- const userData = req.body
-
- try {
- const user = await clerkClient.users.createUser(userData)
- res.status(200).json({ message: 'User created', user })
- } catch (error) {
- console.log(error)
- res.status(500).json({ error: 'Error creating user' })
- }
- })
- ```
-
-
-
- ```bash {{ filename: 'terminal' }}
- curl 'https://api.clerk.com/v1/users' -X POST -H 'Authorization:Bearer {{secret}}' -H 'Content-Type:application/json' -d '{
- "email_address": ["test@example.com"],
- "password": "my-secure-password"
- }'
- ```
-
-
-
-## Delete users
-
-There are two ways to delete users in Clerk: [in the Clerk Dashboard](#in-the-clerk-dashboard) or [using the Backend API](#using-the-backend-api).
+You can create users either [in the Clerk Dashboard](#in-the-clerk-dashboard-2) or [programmatically](#programmatically-2).
### In the Clerk Dashboard
-To delete users in the Clerk Dashboard:
-
-1. At the top of the Clerk Dashboard, select [**Users**](https://dashboard.clerk.com/~/users).
-1. You can either select the user and then in the side navigation menu, select **Delete user**, or select the menu icon on the right side of the user's row and select **Delete user**.
+To create a user in the Clerk Dashboard, navigate to the [**Users**](https://dashboard.clerk.com/~/users) page and select **Create user**.
-### Using the Backend API
+### Programmatically
-You can delete users in your app using Clerk's Backend API.
+To create a user programmatically, you can either [make a request directly to Clerk's Backend API](/docs/reference/backend/user/create-user#backend-api-bapi-endpoint) or use the [`createUser()`](/docs/reference/backend/user/create-user) method as shown in the following example.
-Use the following tabs to see examples of how to delete users using one of the following:
+
-- JS Backend SDK
-- Express
-- cURL
-
-
-
- The following example shows how to delete a user using the JS Backend SDK's [`deleteUser()`](/docs/reference/backend/user/delete-user) method from the `users` sub-api of the `clerkClient` instance.
-
-
-
- ```ts {{ filename: 'route.ts' }}
- export async function DELETE() {
- const userId = 'user_123'
-
- try {
- await clerkClient.users.deleteUser(userId)
- return Response.json({ message: 'User deleted' })
- } catch (error) {
- console.log(error)
- return Response.json({ error: 'Error deleting user' })
- }
- }
- ```
-
-
- If you're using Next.js, you must `await` the instantiation of the `clerkClient` instance, like so:
+## Delete users
- ```ts
- const client = await clerkClient()
+You can delete users either [in the Clerk Dashboard](#in-the-clerk-dashboard-3) or [programmatically](#programmatically-3).
- const response = await client.users.deleteUser(userId)
- ```
-
-
+### In the Clerk Dashboard
-
- ```ts {{ filename: 'delete-user.ts' }}
- import { clerkClient } from '@clerk/express'
+To delete a user in the Clerk Dashboard, navigate to the [**Users**](https://dashboard.clerk.com/~/users) page. You can either select the user and then in the side navigation menu, select **Delete user**, or select the menu icon on the right side of the user's row and select **Delete user**.
- app.post('/deleteUser', async (req, res) => {
- const userId = req.body.userId
+### Programmatically
- try {
- await clerkClient.users.deleteUser(userId)
- res.status(200).json({ message: 'User deleted' })
- } catch (error) {
- console.log(error)
- res.status(500).json({ error: 'Error deleting user' })
- }
- })
- ```
-
+To delete a user programmatically, you can either [make a request directly to Clerk's Backend API](/docs/reference/backend/user/delete-user#backend-api-bapi-endpoint) or use the [`deleteUser()`](/docs/reference/backend/user/delete-user) method as shown in the following example.
-
- ```bash {{ filename: 'terminal' }}
- curl 'https://api.clerk.com/v1/users/{user_id}' -X DELETE -H 'Authorization:Bearer {{secret}}' -H 'Content-Type:application/json'
- ```
-
-
+
diff --git a/docs/guides/users/reading.mdx b/docs/guides/users/reading.mdx
index 3d9a95f323..0b98fa4388 100644
--- a/docs/guides/users/reading.mdx
+++ b/docs/guides/users/reading.mdx
@@ -1,7 +1,7 @@
---
title: Protect content and read user data
description: Learn how to use Clerk's hooks and helpers to protect content and read user data in your Next.js application.
-metadata:
+metadata:
title: Read session and user data in your Next.js app with Clerk
sdk: nextjs
---
@@ -36,7 +36,7 @@ The following example uses the [`auth()`](/docs/reference/nextjs/app-router/auth
return
Sign in to view this page
}
- // Get the Backend API User object when you need access to the user's information
+ // Get the Backend User object when you need access to the user's information
const user = await currentUser()
// Use `user` to render user details or create UI elements
@@ -59,7 +59,7 @@ The following example uses the [`auth()`](/docs/reference/nextjs/app-router/auth
return new NextResponse('Unauthorized', { status: 401 })
}
- // Use `currentUser()` to get the Backend API User object
+ // Use `currentUser()` to get the Backend User object
const user = await currentUser()
// Add your Route Handler's logic with the returned `user` object
@@ -76,9 +76,9 @@ For Next.js applications using the Pages Router, the [`getAuth()`](/docs/referen
In some cases, you may need the full [`Backend User`](/docs/reference/backend/types/backend-user) object of the currently active user. This is helpful if you want to render information, like their first and last name, directly from the server.
-The `clerkClient()` helper returns an instance of the [JS Backend SDK](/docs/js-backend/getting-started/quickstart), which exposes Clerk's Backend API resources through methods such as the [`getUser()`](/docs/reference/backend/user/get-user){{ target: '_blank' }} method. This method returns the full `Backend User` object.
+The `clerkClient()` helper returns an instance of the [JS Backend SDK](/docs/js-backend/getting-started/quickstart), which exposes Clerk's Backend API resources through methods such as the [`getUser()`](/docs/reference/backend/user/get-user){{ target: '_blank' }} method. This method returns the full `Backend User` object. **It does count towards the [Backend API request rate limit](/docs/guides/how-clerk-works/system-limits)** so it's recommended to use the [`useUser()`](/docs/reference/hooks/use-user) hook on the client side when possible and only use `getUser()` when you specifically need user data in a server context.
-In the following example, the `userId` is passed to the Backend SDK's `getUser()` method to get the user's full `Backend User` object.
+In the following example, the `userId` is passed to the JS Backend SDK's `getUser()` method to get the user's full `Backend User` object.
diff --git a/docs/guides/users/reading.remix.mdx b/docs/guides/users/reading.remix.mdx
index 00f2adab93..f2dff9ab9a 100644
--- a/docs/guides/users/reading.remix.mdx
+++ b/docs/guides/users/reading.remix.mdx
@@ -14,9 +14,9 @@ Clerk provides a set of [hooks and helpers](/docs/reference/remix/overview) that
### `getAuth()`
-The [`getAuth()`](/docs/reference/remix/overview#get-auth) helper allows you to access the [`Auth` object](/docs/reference/backend/types/auth-object){{ target: '_blank' }}, which includes the current user's `userId` and the `isAuthenticated` property, which can be used to protect your routes.
+The [`getAuth()`](/docs/reference/remix/overview#get-auth) helper allows you to access the [`Auth` object](/docs/reference/backend/types/auth-object), which includes the current user's `userId` and the `isAuthenticated` property, which can be used to protect your routes.
-In the following example, the `userId` is passed to the JS Backend SDK's [`getUser()`](/docs/reference/backend/user/get-user){{ target: '_blank' }} method to get the user's full `User` object. For information on how to use the JS Backend SDK, see the [JS Backend documentation](/docs/js-backend/getting-started/quickstart){{ target: '_blank' }}.
+In the following example, the `userId` is passed to the JS Backend SDK's [`getUser()`](/docs/reference/backend/user/get-user) method to get the user's full `User` object. For information on how to use the JS Backend SDK, see the [reference documentation](/docs/js-backend/getting-started/quickstart).
diff --git a/docs/guides/users/reading.tanstack-react-start.mdx b/docs/guides/users/reading.tanstack-react-start.mdx
index d2b379d090..a4aacbee01 100644
--- a/docs/guides/users/reading.tanstack-react-start.mdx
+++ b/docs/guides/users/reading.tanstack-react-start.mdx
@@ -1,7 +1,7 @@
---
title: Protect content and read user data
description: Learn how to use Clerk's hooks and helpers to protect content and read user data in your TanStack React Start application.
-metadata:
+metadata:
title: Read session and user data in your Tanstack React Start app with Clerk
sdk: tanstack-react-start
---
@@ -21,14 +21,16 @@ In the following example, the `userId` is passed to the JS Backend SDK's `getUse
```tsx {{ filename: 'src/routes/index.tsx' }}
import { createFileRoute, redirect } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
- import { auth, clerkClient } from '@clerk/tanstack-react-start/server'
+ import { clerkClient, auth } from '@clerk/tanstack-react-start/server'
import { UserButton } from '@clerk/tanstack-react-start'
const authStateFn = createServerFn({ method: 'GET' }).handler(async () => {
- // Use `auth()` to access `isAuthenticated` and the user's ID
+ // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
+ // Accessing the `Auth` object differs depending on the SDK you're using
+ // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
const { isAuthenticated, userId } = await auth()
- // Protect the server function by checking if the user is signed in
+ // Protect the server function from unauthenticated users
if (!isAuthenticated) {
// This might error if you're redirecting to a path that doesn't exist yet
// You can create a sign-in route to handle this
@@ -70,22 +72,31 @@ In the following example, the `userId` is passed to the JS Backend SDK's `getUse
```ts {{ filename: 'src/routes/api/example.ts' }}
import { auth, clerkClient } from '@clerk/tanstack-react-start/server'
import { json } from '@tanstack/react-start'
- import { createServerFileRoute } from '@tanstack/react-start/server'
-
- export const ServerRoute = createServerFileRoute('/api/example').methods({
- GET: async ({ request, params }) => {
- // Use `auth()` to access `isAuthenticated` and the user's ID
- const { isAuthenticated, userId } = await auth()
-
- // Protect the API route by checking if the user is signed in
- if (!isAuthenticated) {
- return json({ error: 'Unauthorized' }, { status: 401 })
- }
-
- // Get the user's full `Backend User` object
- const user = await clerkClient().users.getUser(userId)
-
- return json({ user })
+ import { createFileRoute } from '@tanstack/react-router'
+
+ export const ServerRoute = createFileRoute('/api/example')({
+ server: {
+ handlers: {
+ GET: async () => {
+ // The `Auth` object gives you access to properties like `isAuthenticated` and `userId`
+ // Accessing the `Auth` object differs depending on the SDK you're using
+ // https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object
+ const { isAuthenticated, userId } = await auth()
+
+ // Protect the API route from unauthenticated users
+ if (!isAuthenticated) {
+ return new Response('User not authenticated', {
+ status: 404,
+ })
+ }
+
+ // Get the user's full `Backend User` object
+ const user = await clerkClient().users.getUser(userId)
+
+ // Return the `Backend User` object
+ return json({ user })
+ },
+ },
},
})
```
diff --git a/docs/reference/astro/clerk-middleware.mdx b/docs/reference/astro/clerk-middleware.mdx
index b58376136f..ece546a5a1 100644
--- a/docs/reference/astro/clerk-middleware.mdx
+++ b/docs/reference/astro/clerk-middleware.mdx
@@ -45,7 +45,7 @@ import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server'
const isProtectedRoute = createRouteMatcher(['/dashboard(.*)', '/forum(.*)'])
export const onRequest = clerkMiddleware((auth, context) => {
- const { isAuthenticated, redirectToSignIn, userId } = auth()
+ const { isAuthenticated, redirectToSignIn } = auth()
if (!isAuthenticated && isProtectedRoute(context.request)) {
// Add custom logic to run before redirecting
diff --git a/docs/reference/backend/authenticate-request.mdx b/docs/reference/backend/authenticate-request.mdx
index df4cad9353..dcbe92ecf0 100644
--- a/docs/reference/backend/authenticate-request.mdx
+++ b/docs/reference/backend/authenticate-request.mdx
@@ -109,7 +109,7 @@ It is recommended to set these options as [environment variables](/docs/guides/d
## Examples
-
+
If you are using the [JS Backend SDK](/docs/js-backend/getting-started/quickstart) on its own, you need to provide the `secretKey` and `publishableKey` to `createClerkClient()` so that it is passed to `authenticateRequest()`. You can set these values as [environment variables](/docs/guides/development/clerk-environment-variables#clerk-publishable-and-secret-keys) and then pass them to the function.
@@ -138,23 +138,27 @@ It is recommended to set these options as [environment variables](/docs/guides/d
- `authenticateRequest()` requires `publishableKey` to be set. If you are importing `clerkClient` from a higher-level SDK, such as Next.js, then `clerkClient` infers the `publishableKey` from your [environment variables](/docs/guides/development/clerk-environment-variables#clerk-publishable-and-secret-keys). The following example uses Next.js, but the same logic applies for other frameworks.
+ `authenticateRequest()` requires `publishableKey` to be set. If you are importing `clerkClient` from a higher-level SDK, such as Next.js, then `clerkClient` infers the `publishableKey` from your [environment variables](/docs/guides/development/clerk-environment-variables#clerk-publishable-and-secret-keys). **The following example uses Next.js, but you can use the comments in the example to help you adapt it to other SDKs.**
```tsx
import { clerkClient } from '@clerk/nextjs/server'
+ // Initialize the JS Backend SDK
+ // This varies depending on the SDK you're using
+ // https://clerk.com/docs/js-backend/getting-started/quickstart
const client = await clerkClient()
export async function GET(req: Request) {
+ // Use the `authenticateRequest()` method to verify the token
const { isAuthenticated } = await client.authenticateRequest(req, {
authorizedParties: ['https://example.com'],
})
+ // Protect the route from unauthenticated users
if (!isAuthenticated) {
return Response.json({ status: 401 })
}
- // Perform protected actions
// Add logic to perform protected actions
return Response.json({ message: 'This is a reply' })
@@ -167,31 +171,68 @@ It is recommended to set these options as [environment variables](/docs/guides/d
By default, `authenticateRequest()` will authenticate a session request. To authenticate a machine request, you need to set the `acceptsToken` option to a machine token type, such as `'api_key'`, `'oauth_token'` or `'m2m_token'`.
-```tsx
-import { createClerkClient } from '@clerk/backend'
+
+
+ ```tsx
+ import { createClerkClient } from '@clerk/backend'
+
+ export async function GET(request: Request) {
+ // Initialize the JS Backend SDK
+ // This varies depending on the SDK you're using
+ // https://clerk.com/docs/js-backend/getting-started/quickstart
+ const clerkClient = createClerkClient({
+ secretKey: process.env.CLERK_SECRET_KEY,
+ publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
+ })
-export async function GET(request: Request) {
- const clerkClient = createClerkClient({
- secretKey: process.env.CLERK_SECRET_KEY,
- publishableKey: process.env.CLERK_PUBLISHABLE_KEY,
- })
+ // Use the `authenticateRequest()` method to verify the token
+ const { isAuthenticated } = await clerkClient.authenticateRequest(request, {
+ acceptsToken: 'oauth_token',
+ })
- const { isAuthenticated } = await clerkClient.authenticateRequest(request, {
- acceptsToken: 'oauth_token',
- })
+ // Protect the route from unauthenticated users
+ if (!isAuthenticated) {
+ return Response.json({ status: 401 })
+ }
- if (!isAuthenticated) {
- return Response.json({ status: 401 })
- }
+ // Add logic to perform protected actions
- // Add logic to perform protected actions
- return Response.json({ message: 'This is a machine-to-machine reply' })
-}
-```
+ return Response.json({ message: 'This is a machine-to-machine reply' })
+ }
+ ```
+
-### Networkless token verification
+
+ **This example uses Next.js, but you can use the comments in the example to help you adapt it to other SDKs.**
-{/* Note: this example is duped from /authenticate-request. Probably a good opportunity to use a partial here */}
+ ```tsx
+ import { clerkClient } from '@clerk/nextjs/server'
+
+ // Initialize the JS Backend SDK
+ // This varies depending on the SDK you're using
+ // https://clerk.com/docs/js-backend/getting-started/quickstart
+ const client = await clerkClient()
+
+ export async function GET(req: Request) {
+ // Use the `authenticateRequest()` method to verify the token
+ const { isAuthenticated } = await client.authenticateRequest(request, {
+ acceptsToken: 'oauth_token',
+ })
+
+ // Protect the route from unauthenticated users
+ if (!isAuthenticated) {
+ return Response.json({ status: 401 })
+ }
+
+ // Add logic to perform protected actions
+
+ return Response.json({ message: 'This is a machine-to-machine reply' })
+ }
+ ```
+
+
+
+### Networkless token verification
The following example uses the `authenticateRequest()` method with the [JS Backend SDK](/docs/js-backend/getting-started/quickstart) to verify the token passed by the frontend, and performs a networkless authentication by passing `jwtKey`. This will verify if the user is signed into the application or not.
diff --git a/docs/reference/backend/invitations/create-invitation.mdx b/docs/reference/backend/invitations/create-invitation.mdx
index 8db251453e..9e84ee1d54 100644
--- a/docs/reference/backend/invitations/create-invitation.mdx
+++ b/docs/reference/backend/invitations/create-invitation.mdx
@@ -65,7 +65,7 @@ function createInvitation(params: CreateParams): Promise
The slug of the email template to use for the invitation email. Defaults to `invitation`.
-## Example
+## Usage
@@ -82,6 +82,24 @@ const response = await clerkClient.invitations.createInvitation({
})
```
+## Example
+
+
+
## Backend API (BAPI) endpoint
This method in the SDK is a wrapper around the BAPI endpoint `POST/invitations`. See the [BAPI reference](/docs/reference/backend-api/tag/invitations/post/invitations){{ target: '_blank' }} for more information.
+
+Here's an example of making a request directly to the endpoint using cURL.
+
+
+ Replace the email address with the email address you want to invite. Your Clerk Secret Key is already injected into the code snippet.
+
+
+
+ Replace the email address with the email address you want to invite. Update `YOUR_SECRET_KEY` with your Clerk Secret Key which can be found on the [**API keys**](https://dashboard.clerk.com/~/api-keys) page in the Clerk Dashboard.
+
+
+```bash {{ filename: 'terminal' }}
+curl https://api.clerk.com/v1/invitations -X POST -d '{"email_address": "email@example.com"}' -H "Authorization:Bearer {{secret}}" -H 'Content-Type:application/json'
+```
diff --git a/docs/reference/backend/invitations/revoke-invitation.mdx b/docs/reference/backend/invitations/revoke-invitation.mdx
index 1b0089829b..43d4027bbd 100644
--- a/docs/reference/backend/invitations/revoke-invitation.mdx
+++ b/docs/reference/backend/invitations/revoke-invitation.mdx
@@ -25,7 +25,7 @@ function revokeInvitation(invitationId: string): Promise
The ID of the invitation to revoke.
-## Example
+## Usage
@@ -35,6 +35,24 @@ const invitationId = 'inv_123'
const response = await clerkClient.invitations.revokeInvitation(invitationId)
```
+## Example
+
+
+
## Backend API (BAPI) endpoint
This method in the SDK is a wrapper around the BAPI endpoint `POST/invitations/{invitation_id}/revoke`. See the [BAPI reference](/docs/reference/backend-api/tag/invitations/post/invitations/\{invitation_id}/revoke){{ target: '_blank' }} for more information.
+
+Here's an example of making a request directly to the endpoint using cURL.
+
+
+ Replace the `` with the ID of the invitation you want to revoke. Your Secret Key is already injected into the code snippet.
+
+
+
+ Replace the `` with the ID of the invitation you want to revoke and replace `YOUR_SECRET_KEY` with your Clerk Secret Key. You can find your Secret Key on the [**API keys**](https://dashboard.clerk.com/~/api-keys) page in the Clerk Dashboard.
+
+
+```bash {{ filename: 'terminal' }}
+curl https://api.clerk.com/v1/invitations//revoke -X POST -H "Authorization:Bearer {{secret}}" -H 'Content-Type:application/json'
+```
diff --git a/docs/reference/backend/user/create-user.mdx b/docs/reference/backend/user/create-user.mdx
index 6e87f370c3..dd75b64160 100644
--- a/docs/reference/backend/user/create-user.mdx
+++ b/docs/reference/backend/user/create-user.mdx
@@ -225,7 +225,7 @@ function createUser(params: CreateUserParams): Promise
A custom date/time denoting when the user signed up to the application, specified in [RFC3339 format](https://datatracker.ietf.org/doc/html/rfc3339). For example: `2012-10-20T07:15:20.902Z`.
-## Example
+## Usage
@@ -238,6 +238,19 @@ const response = await clerkClient.users.createUser({
})
```
+## Example
+
+
+
## Backend API (BAPI) endpoint
This method in the SDK is a wrapper around the BAPI endpoint `POST/users`. See the [BAPI reference](/docs/reference/backend-api/tag/users/post/users){{ target: '_blank' }} for more information.
+
+Here's an example of making a request directly to the endpoint using cURL.
+
+```bash {{ filename: 'terminal' }}
+ curl 'https://api.clerk.com/v1/users' -X POST -H 'Authorization:Bearer {{secret}}' -H 'Content-Type:application/json' -d '{
+ "email_address": ["test@example.com"],
+ "password": "my-secure-password"
+ }'
+```
diff --git a/docs/reference/backend/user/delete-user.mdx b/docs/reference/backend/user/delete-user.mdx
index c4fe74e82a..139f865b8c 100644
--- a/docs/reference/backend/user/delete-user.mdx
+++ b/docs/reference/backend/user/delete-user.mdx
@@ -21,7 +21,7 @@ function deleteUser(userId: string): Promise
The ID of the user to delete.
-## Example
+## Usage
@@ -31,6 +31,16 @@ const userId = 'user_123'
const response = await clerkClient.users.deleteUser(userId)
```
+## Example
+
+
+
## Backend API (BAPI) endpoint
This method in the SDK is a wrapper around the BAPI endpoint `DELETE/users/{user_id}`. See the [BAPI reference](/docs/reference/backend-api/tag/users/delete/users/\{user_id}){{ target: '_blank' }} for more information.
+
+Here's an example of making a request directly to the endpoint using cURL.
+
+```bash {{ filename: 'terminal' }}
+ curl 'https://api.clerk.com/v1/users/{user_id}' -X DELETE -H 'Authorization:Bearer {{secret}}' -H 'Content-Type:application/json'
+```
diff --git a/docs/reference/backend/user/update-user-metadata.mdx b/docs/reference/backend/user/update-user-metadata.mdx
index 7c0a244b48..9cd2e2755e 100644
--- a/docs/reference/backend/user/update-user-metadata.mdx
+++ b/docs/reference/backend/user/update-user-metadata.mdx
@@ -39,7 +39,7 @@ function updateUserMetadata(userId: string, params: UpdateUserMetadataParams): P
Metadata that can be read and set only from the [Backend API](/docs/reference/backend-api){{ target: '_blank' }}.
-## Example
+## Usage
@@ -53,6 +53,123 @@ const response = await clerkClient.users.updateUserMetadata(userId, {
})
```
+## Example
+
+This example updates the user's public metadata to include a birthday, but you can update the public, private, or unsafe metadata to include any information you want.
+
+
+
+ ```ts {{ filename: 'app/api/example/route.ts' }}
+ import { auth, clerkClient } from '@clerk/nextjs/server'
+ import { NextResponse } from 'next/server'
+
+ export async function GET() {
+ const { userId } = await auth()
+ const client = await clerkClient()
+
+ await client.users.updateUserMetadata(userId, {
+ publicMetadata: {
+ birthday: '1990-01-01',
+ },
+ })
+
+ return NextResponse.json({ success: true })
+ }
+ ```
+
+
+
+ ```tsx {{ filename: 'src/api/example.ts' }}
+ import type { APIRoute } from 'astro'
+ import { clerkClient } from '@clerk/astro/server'
+
+ export const GET: APIRoute = async (context) => {
+ const { userId } = context.locals.auth()
+
+ await clerkClient(context).users.updateUserMetadata(userId, {
+ publicMetadata: {
+ birthday: '1990-01-01',
+ },
+ })
+
+ return new Response(JSON.stringify({ success: true }), { status: 200 })
+ }
+ ```
+
+
+
+ ```ts {{ filename: 'public.ts' }}
+ import { getAuth, clerkClient } from '@clerk/express'
+
+ app.post('/updateBirthday', async (req, res) => {
+ const { userId } = getAuth(req)
+
+ await clerkClient.users.updateUserMetadata(userId, {
+ publicMetadata: {
+ birthday: '1990-01-01',
+ },
+ })
+ res.status(200).json({ success: true })
+ })
+ ```
+
+
+
+ ```tsx {{ filename: 'app/routes/example.tsx' }}
+ import { clerkClient, getAuth } from '@clerk/react-router/server'
+ import type { Route } from './+types/example'
+
+ export async function loader(args: Route.LoaderArgs) {
+ const { userId } = await getAuth(args)
+
+ await clerkClient.users.updateUserMetadata(userId, {
+ publicMetadata: {
+ birthday: '1990-01-01',
+ },
+ })
+
+ return { success: true }
+ }
+ ```
+
+
+
+ ```tsx {{ filename: 'app/routes/api/example.tsx' }}
+ import { json } from '@tanstack/react-start'
+ import { createFileRoute } from '@tanstack/react-router'
+ import { auth, clerkClient } from '@clerk/tanstack-react-start/server'
+
+ export const ServerRoute = createFileRoute('/api/example')({
+ server: {
+ handlers: {
+ GET: async () => {
+ const { userId } = await auth()
+
+ await clerkClient().users.updateUserMetadata(userId, {
+ publicMetadata: {
+ birthday: '1990-01-01',
+ },
+ })
+
+ return json({ success: true })
+ },
+ },
+ },
+ })
+ ```
+
+
+
## Backend API (BAPI) endpoint
This method in the SDK is a wrapper around the BAPI endpoint `PATCH/users/{user_id}/metadata`. See the [BAPI reference](/docs/reference/backend-api/tag/users/patch/users/\{user_id}/metadata){{ target: '_blank' }} for more information.
+
+Here's an example of making a request directly to the endpoint using cURL.
+
+```bash {{ filename: 'curl.sh' }}
+curl -XPATCH -H 'Authorization: Bearer CLERK_SECRET_KEY' -H "Content-type: application/json" -d '{
+ "public_metadata": {
+ "birthday": "1990-01-01"
+ }
+}' 'https://api.clerk.com/v1/users/{user_id}/metadata'
+```
diff --git a/docs/reference/nextjs/overview.mdx b/docs/reference/nextjs/overview.mdx
index 74fd2fd8e7..bee4876ca3 100644
--- a/docs/reference/nextjs/overview.mdx
+++ b/docs/reference/nextjs/overview.mdx
@@ -34,6 +34,12 @@ Clerk continues to provide drop-in support for the Next.js Pages Router. In addi
- [`getAuth()`](/docs/reference/nextjs/pages-router/get-auth)
- [`buildClerkProps()`](/docs/reference/nextjs/pages-router/build-clerk-props)
+## `clerkClient`
+
+[Clerk's JS Backend SDK](/docs/js-backend/getting-started/quickstart) provides access to Backend API resources and low-level authentication utilities for JavaScript environments. For example, to retrieve a list of all users in your application, you can use the `users.getUserList()` method from the JS Backend SDK instead of manually making a fetch request to the [https://api.clerk.com/v1/users](https://clerk.com/docs/reference/backend-api/tag/users/get/users) endpoint.
+
+All resource operations are mounted as sub-APIs on the `clerkClient` object. See the [reference documentation](/docs/js-backend/getting-started/quickstart#usage) for more information.
+
## `Auth` object
Both `auth()` (App Router) and `getAuth()` (Pages Router) return 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/reference/backend/types/auth-object){{ target: '_blank' }}.