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
6 changes: 6 additions & 0 deletions .changeset/fifty-buses-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@clerk/tanstack-react-start': minor
---

- Fixes serialization errors during handshake
- Bump `@tanstack/react-start` and `@tanstack/react-router` peer dependency to 1.127.0
6 changes: 3 additions & 3 deletions integration/templates/tanstack-react-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
"start": "vite"
},
"dependencies": {
"@tanstack/react-router": "^1.121.27",
"@tanstack/react-router-devtools": "^1.121.27",
"@tanstack/router-plugin": "^1.121.27",
"@tanstack/react-router": "^1.128.0",
"@tanstack/react-router-devtools": "^1.128.0",
"@tanstack/router-plugin": "^1.128.0",
"react": "18.3.1",
"react-dom": "18.3.1"
},
Expand Down
6 changes: 3 additions & 3 deletions integration/templates/tanstack-react-start/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"start": "vite start --port=$PORT"
},
"dependencies": {
"@tanstack/react-router": "^1.121.27",
"@tanstack/react-router-devtools": "^1.121.27",
"@tanstack/react-start": "^1.121.28",
"@tanstack/react-router": "^1.128.0",
"@tanstack/react-router-devtools": "^1.128.0",
"@tanstack/react-start": "^1.128.0",
"react": "18.3.1",
"react-dom": "18.3.1",
"tailwind-merge": "^2.5.4"
Expand Down
29 changes: 29 additions & 0 deletions integration/templates/tanstack-react-start/src/routes/user.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
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';

const fetchClerkAuth = createServerFn({ method: 'GET' }).handler(async () => {
const request = getWebRequest();
if (!request) throw new Error('No request found');

const { userId } = await getAuth(request);

return {
userId,
};
});

export const Route = createFileRoute('/')({
component: Page,
beforeLoad: async () => await fetchClerkAuth(),
loader: async ({ context }) => {
return { userId: context.userId };
},
});
Comment on lines +17 to +23
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the route configuration logic.

The route configuration has several critical issues:

  1. Incorrect beforeLoad implementation: The beforeLoad hook should return data that becomes available in the context
  2. Missing error handling: No handling for failed authentication
  3. Type safety: The loader assumes context.userId exists without validation
 export const Route = createFileRoute('/')({
   component: Page,
-  beforeLoad: async () => await fetchClerkAuth(),
+  beforeLoad: async () => {
+    const authData = await fetchClerkAuth();
+    return authData;
+  },
   loader: async ({ context }) => {
-    return { userId: context.userId };
+    return { userId: (context as any).userId || null };
   },
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const Route = createFileRoute('/')({
component: Page,
beforeLoad: async () => await fetchClerkAuth(),
loader: async ({ context }) => {
return { userId: context.userId };
},
});
export const Route = createFileRoute('/')({
component: Page,
beforeLoad: async () => {
const authData = await fetchClerkAuth();
return authData;
},
loader: async ({ context }) => {
return { userId: (context as any).userId || null };
},
});
🤖 Prompt for AI Agents
In integration/templates/tanstack-react-start/src/routes/user.tsx around lines
17 to 23, fix the route configuration by updating beforeLoad to return the
authentication data so it becomes part of the context, add error handling to
manage failed authentication cases gracefully, and ensure the loader validates
the presence of userId in the context before accessing it to maintain type
safety and avoid runtime errors.


function Page() {
const state = Route.useLoaderData();

return state.userId ? <h1>Welcome! Your ID is {state.userId}!</h1> : <h1>You are not signed in</h1>;
}
23 changes: 22 additions & 1 deletion integration/tests/tanstack-start/basic.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { User } from '@clerk/backend';
import { expect, test } from '@playwright/test';

import { appConfigs } from '../../presets';
Expand All @@ -16,6 +17,7 @@ testAgainstRunningApps({ withEnv: [appConfigs.envs.withEmailCodes] })(
test.describe.configure({ mode: 'parallel' });

let fakeUser: FakeUser;
let bapiUser: User;

test.beforeAll(async () => {
const u = createTestUtils({ app });
Expand All @@ -24,7 +26,7 @@ testAgainstRunningApps({ withEnv: [appConfigs.envs.withEmailCodes] })(
withPhoneNumber: true,
withUsername: true,
});
await u.services.users.createBapiUser(fakeUser);
bapiUser = await u.services.users.createBapiUser(fakeUser);
});

test.afterAll(async () => {
Expand Down Expand Up @@ -72,6 +74,25 @@ testAgainstRunningApps({ withEnv: [appConfigs.envs.withEmailCodes] })(
expect(clerkInitialState !== undefined).toBeTruthy();
});

test('retrieve auth state in server functions', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });

await u.page.goToRelative('/user');

await expect(u.page.getByText('You are not signed in')).toBeVisible();

await u.po.signIn.goTo();

await u.po.signIn.setIdentifier(fakeUser.email);
await u.po.signIn.setPassword(fakeUser.password);
await u.po.signIn.continue();
await u.po.expect.toBeSignedIn();

await u.page.goToRelative('/user');

await expect(u.page.getByText(`Welcome! Your ID is ${bapiUser.id}!`)).toBeVisible();
});

test('clerk handler sets headers', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
const r = await u.po.signIn.goTo();
Expand Down
8 changes: 4 additions & 4 deletions packages/tanstack-react-start/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@
"tslib": "catalog:repo"
},
"devDependencies": {
"@tanstack/react-router": "^1.121.41",
"@tanstack/react-start": "^1.121.41",
"@tanstack/react-router": "^1.127.0",
"@tanstack/react-start": "^1.127.0",
"esbuild-plugin-file-path-extensions": "^2.1.4"
},
"peerDependencies": {
"@tanstack/react-router": "^1.121.0",
"@tanstack/react-start": "^1.121.0",
"@tanstack/react-router": "^1.127.0",
"@tanstack/react-start": "^1.127.0",
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { AuthStatus, constants } from '@clerk/backend/internal';
import { handleNetlifyCacheInDevInstance } from '@clerk/shared/netlifyCacheHandler';

import { errorThrower } from '../utils';
import { ClerkHandshakeRedirect } from './errors';
import { patchRequest } from './utils';

export async function authenticateRequest(
Expand Down Expand Up @@ -41,9 +42,9 @@ export async function authenticateRequest(
requestStateHeaders: requestState.headers,
publishableKey: requestState.publishableKey,
});

// triggering a handshake redirect
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw new Response(null, { status: 307, headers: requestState.headers });
throw new ClerkHandshakeRedirect(307, requestState.headers);
}

if (requestState.status === AuthStatus.Handshake) {
Expand Down
11 changes: 11 additions & 0 deletions packages/tanstack-react-start/src/server/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export class ClerkHandshakeRedirect extends Error {
constructor(
public status: number,
public headers: Headers,
) {
super('Clerk handshake redirect required');
this.name = 'ClerkHandshakeRedirect';
this.status = status;
this.headers = headers;
}
}
8 changes: 6 additions & 2 deletions packages/tanstack-react-start/src/server/middlewareHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { AnyRouter } from '@tanstack/react-router';
import type { CustomizeStartHandler, HandlerCallback, RequestHandler } from '@tanstack/react-start/server';

import { authenticateRequest } from './authenticateRequest';
import { ClerkHandshakeRedirect } from './errors';
import { loadOptions } from './loadOptions';
import type { LoaderOptions } from './types';
import { getResponseClerkState } from './utils';
Expand Down Expand Up @@ -33,9 +34,12 @@ export function createClerkHandler<TRouter extends AnyRouter>(

await router.load();
} catch (error) {
if (error instanceof Response) {
if (error instanceof ClerkHandshakeRedirect) {
// returning the response
return error;
return new Response(null, {
status: error.status,
headers: error.headers,
});
}

// rethrowing the error if it is not a Response
Expand Down
Loading
Loading