Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/_partials/auth-object-table.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ The `Auth` object is available on the `request` object in server contexts. Some
| Express | [`req.auth`](/docs/reference/express/overview) |
| React Router | [`getAuth()`](/docs/reference/react-router/get-auth) |
| Remix | [`getAuth()`](/docs/reference/remix/overview#get-auth) |
| Tanstack React Start | [`getAuth()`](/docs/reference/tanstack-react-start/get-auth) |
| Tanstack React Start | [`auth()`](/docs/reference/tanstack-react-start/auth) |
| Other | `request.auth` |
132 changes: 70 additions & 62 deletions docs/getting-started/quickstart.tanstack-react-start.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ sdk: tanstack-react-start
title: "Set up a Clerk application",
link: "/docs/getting-started/quickstart/setup-clerk",
icon: "clerk",
},
{
title: "Create a TanStack React Start application",
link: "https://tanstack.com/start/latest/docs/framework/react/getting-started",
icon: "tanstack",
}
]}
/>
Expand All @@ -31,23 +36,9 @@ sdk: tanstack-react-start

Run the following command to install the SDK:

<CodeBlockTabs options={["npm", "yarn", "pnpm", "bun"]}>
```bash {{ filename: 'terminal' }}
npm install @clerk/tanstack-react-start
```

```bash {{ filename: 'terminal' }}
yarn add @clerk/tanstack-react-start
```

```bash {{ filename: 'terminal' }}
pnpm add @clerk/tanstack-react-start
```

```bash {{ filename: 'terminal' }}
bun add @clerk/tanstack-react-start
```
</CodeBlockTabs>
```npm {{ filename: 'terminal' }}
npm install @clerk/tanstack-react-start
```

## Set your Clerk API keys

Expand All @@ -68,32 +59,20 @@ sdk: tanstack-react-start
CLERK_SECRET_KEY={{secret}}
```

## Add `createClerkHandler()`
## Add `clerkMiddleware()` to your app

TanStack's [`createStartHandler()`](https://tanstack.com/router/latest/docs/framework/react/start/getting-started#the-server-entry-point) creates a server-side handler that determines which routes and loaders need to be executed when the user hits a given route.
[`clerkMiddleware()`](/docs/reference/tanstack-react-start/clerk-middleware) grants you access to user authentication state throughout your app, on any server function or route.

Clerk's [`createClerkHandler()`](/docs/reference/tanstack-react-start/create-clerk-handler) configures Clerk to handle authentication state for TanStack routes, allowing you to easily access user session information within your app.
Create a `src/start.ts` file with the following code:

Create a custom handler and wrap it with `createClerkHandler()`, as shown in the following example:
```tsx {{ filename: 'src/start.ts' }}
import { clerkMiddleware } from '@clerk/tanstack-react-start/server'
import { createStart } from '@tanstack/react-start'

```tsx {{ filename: 'src/server.ts' }}
import {
createStartHandler,
defaultStreamHandler,
defineHandlerCallback,
} from '@tanstack/react-start/server'
import { createRouter } from './router'
import { createClerkHandler } from '@clerk/tanstack-react-start/server'

const handlerFactory = createClerkHandler(
createStartHandler({
createRouter,
}),
)

export default defineHandlerCallback(async (event) => {
const startHandler = await handlerFactory(defaultStreamHandler)
return startHandler(event)
export const startInstance = createStart(() => {
return {
requestMiddleware: [clerkMiddleware()],
}
})
```

Expand All @@ -103,30 +82,62 @@ sdk: tanstack-react-start

Add the `<ClerkProvider>` component to your app's root route, as shown in the following example:

```tsx {{ filename: 'src/routes/__root.tsx', ins: [3, 17, 27] }}
import * as React from 'react'
import { HeadContent, Outlet, Scripts, createRootRoute } from '@tanstack/react-router'
```tsx {{ filename: 'src/routes/__root.tsx', ins: [1, 37, 59], fold: [[2, 34]] }}
import { ClerkProvider } from '@clerk/tanstack-react-start'
import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
import { TanStackDevtools } from '@tanstack/react-devtools'

import Header from '../components/Header'

import appCss from '../styles.css?url'

export const Route = createRootRoute({
component: () => {
return (
<RootDocument>
<Outlet />
</RootDocument>
)
},
head: () => ({
meta: [
{
charSet: 'utf-8',
},
{
name: 'viewport',
content: 'width=device-width, initial-scale=1',
},
{
title: 'TanStack Start Starter',
},
],
links: [
{
rel: 'stylesheet',
href: appCss,
},
],
}),

shellComponent: RootDocument,
})

function RootDocument({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider>
<html>
<html lang="en">
<head>
<HeadContent />
</head>
<body>
<Header />
{children}
<TanStackDevtools
config={{
position: 'bottom-right',
}}
plugins={[
{
name: 'Tanstack Router',
render: <TanStackRouterDevtoolsPanel />,
},
]}
/>
<Scripts />
</body>
</html>
Expand Down Expand Up @@ -175,21 +186,18 @@ sdk: tanstack-react-start

### Server-side

To protect your routes, create a [server function](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions) that checks the user's authentication state via the [`getAuth()`](/docs/reference/tanstack-react-start/get-auth) method. If the user is not authenticated, they are redirected to a sign-in page. If authenticated, the user's `userId` is passed to the route, allowing access to the `<Home />` component, which welcomes the user and displays their `userId`. The [`beforeLoad()`](https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType#beforeload-method) method ensures authentication is checked before loading the page, and the [`loader()`](https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType#loader-method) method returns the user data for use in the component.
To protect your routes, create a [server function](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions) that checks the user's authentication state via the [`auth()`](/docs/reference/tanstack-react-start/auth) method. If the user is not authenticated, they are redirected to a sign-in page. If authenticated, the user's `userId` is passed to the route, allowing access to the `<Home />` component, which welcomes the user and displays their `userId`. The [`beforeLoad()`](https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType#beforeload-method) method ensures authentication is checked before loading the page, and the [`loader()`](https://tanstack.com/router/latest/docs/framework/react/api/router/RouteOptionsType#loader-method) method returns the user data for use in the component.

> [!TIP]
> Ensure that your app has the [TanStack Start server handler](https://tanstack.com/start/latest/docs/framework/react/guide/server-routes#handling-server-route-requests) configured in order for your server routes to work.

```tsx {{ filename: 'src/routes/index.tsx' }}
import { createFileRoute, redirect } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { getAuth } from '@clerk/tanstack-react-start/server'
import { getWebRequest } from '@tanstack/react-start/server'
import { auth } from '@clerk/tanstack-react-start/server'

const authStateFn = createServerFn({ method: 'GET' }).handler(async () => {
const request = getWebRequest()
if (!request) throw new Error('No request found')
const { isAuthenticated, userId } = await getAuth(request)
const { isAuthenticated, userId } = await auth()

if (!isAuthenticated) {
// This will error because you're redirecting to a path that doesn't exist yet
Expand Down Expand Up @@ -246,18 +254,18 @@ sdk: tanstack-react-start
## Next steps

<Cards>
- [Create a custom sign-in-or-up page](/docs/tanstack-react-start/guides/development/custom-sign-in-or-up-page)
- Learn how add custom sign-in-or-up page with Clerk components.
- [Core concepts](/docs/getting-started/core-concepts)
- Before building your application, it's important to understand the core concepts and objects that drive Clerk's powerful authentication and user management system.

---

- [Protect content and read user data](/docs/tanstack-react-start/guides/users/reading)
- Learn how to use Clerk's hooks and helpers to access the session and user data in your TanStack React Start app.
- [Add a custom sign-in-or-up page](/docs/tanstack-react-start/guides/development/custom-sign-in-or-up-page)
- Learn how to create a custom sign-in-or-up page using Clerk's prebuilt components.

---

- [Customization & localization](/docs/guides/customizing-clerk/appearance-prop/overview)
- Learn how to customize and localize the Clerk components.
- [Protect content and read user data](/docs/tanstack-react-start/guides/users/reading)
- Learn how to use Clerk's hooks and helpers to protect content and read session and user data.

---

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,24 @@ When building a resource server that needs to accept and verify OAuth access tok

<Include src="_partials/machine-token-pricing-callout" />

Clerk provides a built-in [`getAuth()`](/docs/reference/tanstack-react-start/get-auth) function that supports token validation via the `acceptsToken` parameter. This lets you specify which type(s) of token your API route should accept in your TanStack React Start application.
Clerk provides a built-in [`auth()`](/docs/reference/tanstack-react-start/auth) function that supports token validation via the `acceptsToken` parameter. This lets you specify which type(s) of token your API route should accept in your TanStack React Start application.

By default, `acceptsToken` is set to `session_token`, which means OAuth tokens will **not** be accepted unless explicitly configured. You can pass either a **single token type** or an **array of token types** to `acceptsToken`. To learn more about the supported token types, see the [`getAuth()` parameters documentation](/docs/reference/tanstack-react-start/get-auth#parameters).
By default, `acceptsToken` is set to `session_token`, which means OAuth tokens will **not** be accepted unless explicitly configured. You can pass either a **single token type** or an **array of token types** to `acceptsToken`. To learn more about the supported token types, see the [`auth()` parameters documentation](/docs/reference/tanstack-react-start/auth#parameters).

## Example 1: Accepting a single token type

In the following example, the `acceptsToken` parameter is set to only accept `oauth_token`s.

- If the token is invalid or missing, `getAuth()` will return `null` for `subject` and other properties, and the request will be rejected with a `401` response.
- If the token is invalid or missing, `auth()` will return `null` for `subject` and other properties, and the request will be rejected with a `401` response.
- If the token is valid, it returns the authenticated user's subject and their associated scopes for use in the application logic.

```tsx
export async function clerkAuth({ request }: { request: Request }) {
const { subject, scopes } = await getAuth(request, {
const { subject, scopes } = await auth({
acceptsToken: 'oauth_token',
})

// If getAuth() returns null, the token is invalid
// If auth() returns null, the token is invalid
if (!subject) {
throw new Error('OAuth access token is invalid')
}
Expand All @@ -43,12 +43,10 @@ In the following example, the `acceptsToken` parameter is set to accept any toke

```tsx
import { createServerFn } from '@tanstack/react-start'
import { getAuth } from '@clerk/tanstack-react-start/server'
import { getWebRequest } from '@tanstack/react-start/server'
import { auth } from '@clerk/tanstack-react-start/server'

const authStateFn = createServerFn({ method: 'GET' }).handler(async () => {
const request = getWebRequest()
const { tokenType } = await getAuth(request, { acceptsToken: 'any' })
const { tokenType } = await auth({ acceptsToken: 'any' })

if (tokenType === 'session_token') {
console.log('This is a session token from a user')
Expand Down
2 changes: 1 addition & 1 deletion docs/guides/users/reading.react-router.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ To access active session and user data on the server-side, use the [`getAuth()`]

### Server data loading

The [`getAuth()`](/docs/reference/tanstack-react-start/get-auth) helper returns the [`Auth`](/docs/reference/backend/types/auth-object) object of the currently active user, which contains important information like the current user's session ID, user ID, and organization ID, and the `isAuthenticated` property, which can be used to protect your API routes.
The [`getAuth()`](/docs/reference/react-router/get-auth) helper returns the [`Auth`](/docs/reference/backend/types/auth-object) object of the currently active user, which contains important information like the current user's session ID, user ID, and organization ID, and the `isAuthenticated` property, which can be used to protect your API routes.

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.

Expand Down
15 changes: 7 additions & 8 deletions docs/guides/users/reading.tanstack-react-start.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Clerk provides a set of [hooks and helpers](/docs/reference/tanstack-react-start

## Server-side

The [`getAuth()`](/docs/reference/tanstack-react-start/get-auth) helper returns the [`Auth`](/docs/reference/backend/types/auth-object) object of the currently active user, which contains important information like the current user's session ID, user ID, and organization ID, and the `isAuthenticated` property, which can be used to protect your API routes.
The [`auth()`](/docs/reference/tanstack-react-start/auth) helper returns the [`Auth`](/docs/reference/backend/types/auth-object) object of the currently active user, which contains important information like the current user's session ID, user ID, and organization ID, and the `isAuthenticated` property, which can be used to protect your API routes.

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.

Expand All @@ -21,13 +21,12 @@ 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 { clerkClient, getAuth } from '@clerk/tanstack-react-start/server'
import { getWebRequest } from '@tanstack/react-start/server'
import { auth, clerkClient } from '@clerk/tanstack-react-start/server'
import { UserButton } from '@clerk/tanstack-react-start'

const authStateFn = createServerFn({ method: 'GET' }).handler(async () => {
// Use `getAuth()` to access `isAuthenticated` and the user's ID
const { isAuthenticated, userId } = await getAuth(getWebRequest())
// Use `auth()` to access `isAuthenticated` and the user's ID
const { isAuthenticated, userId } = await auth()

// Protect the server function by checking if the user is signed in
if (!isAuthenticated) {
Expand Down Expand Up @@ -69,14 +68,14 @@ In the following example, the `userId` is passed to the JS Backend SDK's `getUse

<Tab>
```ts {{ filename: 'src/routes/api/example.ts' }}
import { clerkClient, getAuth } from '@clerk/tanstack-react-start/server'
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 `getAuth()` to access `isAuthenticated` and the user's ID
const { isAuthenticated, userId } = await getAuth(request)
// 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) {
Expand Down
8 changes: 4 additions & 4 deletions docs/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2131,12 +2131,12 @@
"href": "/docs/reference/tanstack-react-start/overview"
},
{
"title": "`getAuth()`",
"href": "/docs/reference/tanstack-react-start/get-auth"
"title": "`auth()`",
"href": "/docs/reference/tanstack-react-start/auth"
},
{
"title": "`createClerkHandler()`",
"href": "/docs/reference/tanstack-react-start/create-clerk-handler"
"title": "`clerkMiddleware()`",
"href": "/docs/reference/tanstack-react-start/clerk-middleware"
}
]
]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
---
title: '`getAuth()`'
description: The getAuth() helper retrieves the authentication state allowing you to protect your API routes or gather relevant data.
title: '`auth()`'
description: The auth() helper retrieves the authentication state allowing you to protect your API routes or gather relevant data.
sdk: tanstack-react-start
---

The `getAuth()` helper retrieves authentication state from the request object.
The `auth()` helper returns the [`Auth`](/docs/reference/backend/types/auth-object){{ target: '_blank' }} object of the currently active user.

## Parameters

<Properties>
- `request`

The request object.

---

- `opts?`
- `{acceptsToken: TokenType, treatPendingAsSignedOut: boolean }`

An optional object that can be used to configure the behavior of the `getAuth()` function. It accepts the following properties:
An optional object that can be used to configure the behavior of the `auth()` function. It accepts the following properties:

<Include src="_partials/machine-auth/accepts-token-explanation" />

Expand All @@ -27,7 +21,7 @@ The `getAuth()` helper retrieves authentication state from the request object.

## Returns

`getAuth()` returns the [`Auth`](/docs/reference/backend/types/auth-object){{ target: '_blank' }} object.
`auth()` returns the [`Auth`](/docs/reference/backend/types/auth-object){{ target: '_blank' }} object.

## Usage

Expand Down
Loading