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
16 changes: 16 additions & 0 deletions .changeset/react-router-v8-support.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
---
'@clerk/react-router': minor
---

Add support for React Router v8.

If you're using React Router v7, keep the `v8_middleware` future flag enabled. If you're migrating to React Router v8, remove the flag:

```diff
// react-router.config.ts
export default {
- future: {
- v8_middleware: true,
- },
}
```
24 changes: 12 additions & 12 deletions integration/templates/react-router-node/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,20 +9,20 @@
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
"@react-router/node": "8.0.1",
"@react-router/serve": "8.0.1",
"isbot": "^5.1.36",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "8.0.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"@react-router/dev": "8.0.1",
"@types/node": "^22",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3",
"vite": "^8.0.3",
"vite-tsconfig-paths": "^5.1.4"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,4 @@ export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
11 changes: 9 additions & 2 deletions integration/templates/react-router-node/vite.config.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,21 @@ import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
export default defineConfig(({ command }) => ({
plugins: [
reactRouter(),
tsconfigPaths({
projects: ['./tsconfig.json'],
}),
],
// Dev-only: `react-router dev` externalizes @clerk/react-router for SSR, so Node
// loads it with a different react-router export condition (production) than Vite
// gives the app (development). That yields two react-router instances and breaks
// the Router context. noExternal routes Clerk through Vite so they share one
// instance. Not applied to `build`, where bundling Clerk fails and the production
// server resolves a single react-router instance anyway.
...(command === 'serve' ? { ssr: { noExternal: ['@clerk/react-router'] } } : {}),
Comment on lines +12 to +18

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

Already talking to a react-router dev about this. There's an upstream issue in dev mode in v8 and to fix it, devs need to add @clerk/react-router to ssr.noExternal.

This should be handled upstream in the following releases. If we got any report of it for v8 users, we can instruct the fix

server: {
port: process.env.PORT ? Number(process.env.PORT) : undefined,
},
});
}));
80 changes: 80 additions & 0 deletions integration/tests/react-router/basic-v7.test.ts

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

v7 smoke test to make sure our package is backwards compat

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../../models/application';
import { appConfigs } from '../../presets';
import { createTestUtils } from '../../testUtils';

const reactRouterV7PackageJson = `{
"name": "clerk-react-router-quickstart",
"private": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "react-router dev --port $PORT",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"vite-tsconfig-paths": "^5.1.4"
}
}
`;

const reactRouterV7Config = `import type { Config } from '@react-router/dev/config';

export default {
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
`;

test.describe('React Router v7 compatibility @react-router', () => {
test.describe.configure({ mode: 'serial' });

let app: Application;

test.beforeAll(async () => {
app = await appConfigs.reactRouter.reactRouterNode
.clone()
.addFile('package.json', () => reactRouterV7PackageJson)
.addFile('react-router.config.ts', () => reactRouterV7Config)
.commit();

await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodes);
await app.dev();
});

test.afterAll(async () => {
await app?.teardown();
});

test('redirects unauthenticated protected route requests through v7 middleware context', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });

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

await expect(u.page).toHaveURL(`${app.serverUrl}/sign-in`);
await u.po.signIn.waitForMounted();
});
});
2 changes: 1 addition & 1 deletion packages/react-router/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@
"peerDependencies": {
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react",
"react-router": "^7.9.0"
"react-router": "^7.9.0 || ^8.0.0"
},
"engines": {
"node": ">=20.9.0"
Expand Down
9 changes: 2 additions & 7 deletions packages/react-router/src/server/clerkMiddleware.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,14 +25,9 @@ export const requestStateContext = createContext<RequestStateContextValue | null
* It checks the request's cookies and headers for a session JWT and, if found,
* attaches the Auth object to a context.
*
* @example
* // react-router.config.ts
* export default {
* future: {
* v8_middleware: true,
* },
* }
* If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
*
* @example
* // root.tsx
* export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
*/
Expand Down
19 changes: 13 additions & 6 deletions packages/react-router/src/server/utils.ts
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
import type { RequestState } from '@clerk/backend/internal';
import { constants, debugRequestState } from '@clerk/backend/internal';
import { parse as parseCookie } from 'cookie';
import type { AppLoadContext, UNSAFE_DataWithResponseInit } from 'react-router';
import type { UNSAFE_DataWithResponseInit } from 'react-router';

import { getPublicEnvVariables } from '../utils/env';
import { canUseKeyless } from '../utils/feature-flags';
import type { AdditionalStateOptions } from './types';

// AppLoadContext was removed from React Router v8. Keep a structural type for the context shape we use.
type ReactRouterContext = Record<string, any> & {
get?: <T>(context: unknown) => T | undefined;
set?: <T>(context: unknown, value: T) => void;
};

export function isResponse(value: any): value is Response {
return (
value != null &&
Expand DownExpand Up@@ -43,17 +49,18 @@ export function assertValidHandlerResult(val: any, error?: string): asserts val
}

/**
* `get` and `set` properties will only be available if v8_middleware flag is enabled
* See: https://reactrouter.com/upgrading/future#futurev8_middleware
* `get` and `set` properties are available when React Router middleware is enabled.
*/
export const IsOptIntoMiddleware = (context: AppLoadContext) => {
export const IsOptIntoMiddleware = (
context: ReactRouterContext,
): context is ReactRouterContext & Required<Pick<ReactRouterContext, 'get' | 'set'>> => {
return 'get' in context && 'set' in context;
};

export const injectRequestStateIntoResponse = async (
response: Response,
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
includeClerkHeaders = false,
) => {
Expand DownExpand Up@@ -82,7 +89,7 @@ export const injectRequestStateIntoResponse = async (
*/
export function getResponseClerkState(
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
) {
const { reason, message, isSignedIn, ...rest } = requestState;
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router/src/utils/env.ts
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
import { getEnvVariable } from '@clerk/shared/getEnvVariable';
import { isTruthy } from '@clerk/shared/underscore';
import type { AppLoadContext } from 'react-router';

export const getPublicEnvVariables = (context: AppLoadContext | undefined) => {
export const getPublicEnvVariables = (context: object | undefined) => {
const getValue = (name: string): string => {
return getEnvVariable(`VITE_${name}`, context) || getEnvVariable(name, context);
return (
getEnvVariable(`VITE_${name}`, context as Record<string, any>) ||
getEnvVariable(name, context as Record<string, any>)
);
};

return {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(react-router): Add support for React Router v8 by wobsoriano · Pull Request #8972 · clerk/javascript · GitHub
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
16 changes: 16 additions & 0 deletions .changeset/react-router-v8-support.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
---
'@clerk/react-router': minor
---

Add support for React Router v8.

If you're using React Router v7, keep the `v8_middleware` future flag enabled. If you're migrating to React Router v8, remove the flag:

```diff
// react-router.config.ts
export default {
- future: {
- v8_middleware: true,
- },
}
```
24 changes: 12 additions & 12 deletions integration/templates/react-router-node/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,20 +9,20 @@
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
"@react-router/node": "8.0.1",
"@react-router/serve": "8.0.1",
"isbot": "^5.1.36",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "8.0.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"@react-router/dev": "8.0.1",
"@types/node": "^22",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3",
"vite": "^8.0.3",
"vite-tsconfig-paths": "^5.1.4"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,4 @@ export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
11 changes: 9 additions & 2 deletions integration/templates/react-router-node/vite.config.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,21 @@ import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
export default defineConfig(({ command }) => ({
plugins: [
reactRouter(),
tsconfigPaths({
projects: ['./tsconfig.json'],
}),
],
// Dev-only: `react-router dev` externalizes @clerk/react-router for SSR, so Node
// loads it with a different react-router export condition (production) than Vite
// gives the app (development). That yields two react-router instances and breaks
// the Router context. noExternal routes Clerk through Vite so they share one
// instance. Not applied to `build`, where bundling Clerk fails and the production
// server resolves a single react-router instance anyway.
...(command === 'serve' ? { ssr: { noExternal: ['@clerk/react-router'] } } : {}),
Comment on lines +12 to +18

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

Already talking to a react-router dev about this. There's an upstream issue in dev mode in v8 and to fix it, devs need to add @clerk/react-router to ssr.noExternal.

This should be handled upstream in the following releases. If we got any report of it for v8 users, we can instruct the fix

server: {
port: process.env.PORT ? Number(process.env.PORT) : undefined,
},
});
}));
80 changes: 80 additions & 0 deletions integration/tests/react-router/basic-v7.test.ts

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

v7 smoke test to make sure our package is backwards compat

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../../models/application';
import { appConfigs } from '../../presets';
import { createTestUtils } from '../../testUtils';

const reactRouterV7PackageJson = `{
"name": "clerk-react-router-quickstart",
"private": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "react-router dev --port $PORT",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"vite-tsconfig-paths": "^5.1.4"
}
}
`;

const reactRouterV7Config = `import type { Config } from '@react-router/dev/config';

export default {
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
`;

test.describe('React Router v7 compatibility @react-router', () => {
test.describe.configure({ mode: 'serial' });

let app: Application;

test.beforeAll(async () => {
app = await appConfigs.reactRouter.reactRouterNode
.clone()
.addFile('package.json', () => reactRouterV7PackageJson)
.addFile('react-router.config.ts', () => reactRouterV7Config)
.commit();

await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodes);
await app.dev();
});

test.afterAll(async () => {
await app?.teardown();
});

test('redirects unauthenticated protected route requests through v7 middleware context', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });

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

await expect(u.page).toHaveURL(`${app.serverUrl}/sign-in`);
await u.po.signIn.waitForMounted();
});
});
2 changes: 1 addition & 1 deletion packages/react-router/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@
"peerDependencies": {
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react",
"react-router": "^7.9.0"
"react-router": "^7.9.0 || ^8.0.0"
},
"engines": {
"node": ">=20.9.0"
Expand Down
9 changes: 2 additions & 7 deletions packages/react-router/src/server/clerkMiddleware.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,14 +25,9 @@ export const requestStateContext = createContext<RequestStateContextValue | null
* It checks the request's cookies and headers for a session JWT and, if found,
* attaches the Auth object to a context.
*
* @example
* // react-router.config.ts
* export default {
* future: {
* v8_middleware: true,
* },
* }
* If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
*
* @example
* // root.tsx
* export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
*/
Expand Down
19 changes: 13 additions & 6 deletions packages/react-router/src/server/utils.ts
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
import type { RequestState } from '@clerk/backend/internal';
import { constants, debugRequestState } from '@clerk/backend/internal';
import { parse as parseCookie } from 'cookie';
import type { AppLoadContext, UNSAFE_DataWithResponseInit } from 'react-router';
import type { UNSAFE_DataWithResponseInit } from 'react-router';

import { getPublicEnvVariables } from '../utils/env';
import { canUseKeyless } from '../utils/feature-flags';
import type { AdditionalStateOptions } from './types';

// AppLoadContext was removed from React Router v8. Keep a structural type for the context shape we use.
type ReactRouterContext = Record<string, any> & {
get?: <T>(context: unknown) => T | undefined;
set?: <T>(context: unknown, value: T) => void;
};

export function isResponse(value: any): value is Response {
return (
value != null &&
Expand DownExpand Up@@ -43,17 +49,18 @@ export function assertValidHandlerResult(val: any, error?: string): asserts val
}

/**
* `get` and `set` properties will only be available if v8_middleware flag is enabled
* See: https://reactrouter.com/upgrading/future#futurev8_middleware
* `get` and `set` properties are available when React Router middleware is enabled.
*/
export const IsOptIntoMiddleware = (context: AppLoadContext) => {
export const IsOptIntoMiddleware = (
context: ReactRouterContext,
): context is ReactRouterContext & Required<Pick<ReactRouterContext, 'get' | 'set'>> => {
return 'get' in context && 'set' in context;
};

export const injectRequestStateIntoResponse = async (
response: Response,
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
includeClerkHeaders = false,
) => {
Expand DownExpand Up@@ -82,7 +89,7 @@ export const injectRequestStateIntoResponse = async (
*/
export function getResponseClerkState(
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
) {
const { reason, message, isSignedIn, ...rest } = requestState;
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router/src/utils/env.ts
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
import { getEnvVariable } from '@clerk/shared/getEnvVariable';
import { isTruthy } from '@clerk/shared/underscore';
import type { AppLoadContext } from 'react-router';

export const getPublicEnvVariables = (context: AppLoadContext | undefined) => {
export const getPublicEnvVariables = (context: object | undefined) => {
const getValue = (name: string): string => {
return getEnvVariable(`VITE_${name}`, context) || getEnvVariable(name, context);
return (
getEnvVariable(`VITE_${name}`, context as Record<string, any>) ||
getEnvVariable(name, context as Record<string, any>)
);
};

return {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(react-router): Add support for React Router v8 by wobsoriano · Pull Request #8972 · clerk/javascript · GitHub
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
16 changes: 16 additions & 0 deletions .changeset/react-router-v8-support.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
---
'@clerk/react-router': minor
---

Add support for React Router v8.

If you're using React Router v7, keep the `v8_middleware` future flag enabled. If you're migrating to React Router v8, remove the flag:

```diff
// react-router.config.ts
export default {
- future: {
- v8_middleware: true,
- },
}
```
24 changes: 12 additions & 12 deletions integration/templates/react-router-node/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,20 +9,20 @@
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
"@react-router/node": "8.0.1",
"@react-router/serve": "8.0.1",
"isbot": "^5.1.36",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "8.0.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"@react-router/dev": "8.0.1",
"@types/node": "^22",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3",
"vite": "^8.0.3",
"vite-tsconfig-paths": "^5.1.4"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,4 @@ export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
11 changes: 9 additions & 2 deletions integration/templates/react-router-node/vite.config.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,21 @@ import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
export default defineConfig(({ command }) => ({
plugins: [
reactRouter(),
tsconfigPaths({
projects: ['./tsconfig.json'],
}),
],
// Dev-only: `react-router dev` externalizes @clerk/react-router for SSR, so Node
// loads it with a different react-router export condition (production) than Vite
// gives the app (development). That yields two react-router instances and breaks
// the Router context. noExternal routes Clerk through Vite so they share one
// instance. Not applied to `build`, where bundling Clerk fails and the production
// server resolves a single react-router instance anyway.
...(command === 'serve' ? { ssr: { noExternal: ['@clerk/react-router'] } } : {}),
Comment on lines +12 to +18

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

Already talking to a react-router dev about this. There's an upstream issue in dev mode in v8 and to fix it, devs need to add @clerk/react-router to ssr.noExternal.

This should be handled upstream in the following releases. If we got any report of it for v8 users, we can instruct the fix

server: {
port: process.env.PORT ? Number(process.env.PORT) : undefined,
},
});
}));
80 changes: 80 additions & 0 deletions integration/tests/react-router/basic-v7.test.ts

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

v7 smoke test to make sure our package is backwards compat

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../../models/application';
import { appConfigs } from '../../presets';
import { createTestUtils } from '../../testUtils';

const reactRouterV7PackageJson = `{
"name": "clerk-react-router-quickstart",
"private": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "react-router dev --port $PORT",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"vite-tsconfig-paths": "^5.1.4"
}
}
`;

const reactRouterV7Config = `import type { Config } from '@react-router/dev/config';

export default {
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
`;

test.describe('React Router v7 compatibility @react-router', () => {
test.describe.configure({ mode: 'serial' });

let app: Application;

test.beforeAll(async () => {
app = await appConfigs.reactRouter.reactRouterNode
.clone()
.addFile('package.json', () => reactRouterV7PackageJson)
.addFile('react-router.config.ts', () => reactRouterV7Config)
.commit();

await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodes);
await app.dev();
});

test.afterAll(async () => {
await app?.teardown();
});

test('redirects unauthenticated protected route requests through v7 middleware context', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });

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

await expect(u.page).toHaveURL(`${app.serverUrl}/sign-in`);
await u.po.signIn.waitForMounted();
});
});
2 changes: 1 addition & 1 deletion packages/react-router/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@
"peerDependencies": {
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react",
"react-router": "^7.9.0"
"react-router": "^7.9.0 || ^8.0.0"
},
"engines": {
"node": ">=20.9.0"
Expand Down
9 changes: 2 additions & 7 deletions packages/react-router/src/server/clerkMiddleware.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,14 +25,9 @@ export const requestStateContext = createContext<RequestStateContextValue | null
* It checks the request's cookies and headers for a session JWT and, if found,
* attaches the Auth object to a context.
*
* @example
* // react-router.config.ts
* export default {
* future: {
* v8_middleware: true,
* },
* }
* If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
*
* @example
* // root.tsx
* export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
*/
Expand Down
19 changes: 13 additions & 6 deletions packages/react-router/src/server/utils.ts
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
import type { RequestState } from '@clerk/backend/internal';
import { constants, debugRequestState } from '@clerk/backend/internal';
import { parse as parseCookie } from 'cookie';
import type { AppLoadContext, UNSAFE_DataWithResponseInit } from 'react-router';
import type { UNSAFE_DataWithResponseInit } from 'react-router';

import { getPublicEnvVariables } from '../utils/env';
import { canUseKeyless } from '../utils/feature-flags';
import type { AdditionalStateOptions } from './types';

// AppLoadContext was removed from React Router v8. Keep a structural type for the context shape we use.
type ReactRouterContext = Record<string, any> & {
get?: <T>(context: unknown) => T | undefined;
set?: <T>(context: unknown, value: T) => void;
};

export function isResponse(value: any): value is Response {
return (
value != null &&
Expand DownExpand Up@@ -43,17 +49,18 @@ export function assertValidHandlerResult(val: any, error?: string): asserts val
}

/**
* `get` and `set` properties will only be available if v8_middleware flag is enabled
* See: https://reactrouter.com/upgrading/future#futurev8_middleware
* `get` and `set` properties are available when React Router middleware is enabled.
*/
export const IsOptIntoMiddleware = (context: AppLoadContext) => {
export const IsOptIntoMiddleware = (
context: ReactRouterContext,
): context is ReactRouterContext & Required<Pick<ReactRouterContext, 'get' | 'set'>> => {
return 'get' in context && 'set' in context;
};

export const injectRequestStateIntoResponse = async (
response: Response,
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
includeClerkHeaders = false,
) => {
Expand DownExpand Up@@ -82,7 +89,7 @@ export const injectRequestStateIntoResponse = async (
*/
export function getResponseClerkState(
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
) {
const { reason, message, isSignedIn, ...rest } = requestState;
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router/src/utils/env.ts
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
import { getEnvVariable } from '@clerk/shared/getEnvVariable';
import { isTruthy } from '@clerk/shared/underscore';
import type { AppLoadContext } from 'react-router';

export const getPublicEnvVariables = (context: AppLoadContext | undefined) => {
export const getPublicEnvVariables = (context: object | undefined) => {
const getValue = (name: string): string => {
return getEnvVariable(`VITE_${name}`, context) || getEnvVariable(name, context);
return (
getEnvVariable(`VITE_${name}`, context as Record<string, any>) ||
getEnvVariable(name, context as Record<string, any>)
);
};

return {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(react-router): Add support for React Router v8 by wobsoriano · Pull Request #8972 · clerk/javascript · GitHub
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
16 changes: 16 additions & 0 deletions .changeset/react-router-v8-support.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
---
'@clerk/react-router': minor
---

Add support for React Router v8.

If you're using React Router v7, keep the `v8_middleware` future flag enabled. If you're migrating to React Router v8, remove the flag:

```diff
// react-router.config.ts
export default {
- future: {
- v8_middleware: true,
- },
}
```
24 changes: 12 additions & 12 deletions integration/templates/react-router-node/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,20 +9,20 @@
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
"@react-router/node": "8.0.1",
"@react-router/serve": "8.0.1",
"isbot": "^5.1.36",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "8.0.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"@react-router/dev": "8.0.1",
"@types/node": "^22",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3",
"vite": "^8.0.3",
"vite-tsconfig-paths": "^5.1.4"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,4 @@ export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
11 changes: 9 additions & 2 deletions integration/templates/react-router-node/vite.config.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,21 @@ import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
export default defineConfig(({ command }) => ({
plugins: [
reactRouter(),
tsconfigPaths({
projects: ['./tsconfig.json'],
}),
],
// Dev-only: `react-router dev` externalizes @clerk/react-router for SSR, so Node
// loads it with a different react-router export condition (production) than Vite
// gives the app (development). That yields two react-router instances and breaks
// the Router context. noExternal routes Clerk through Vite so they share one
// instance. Not applied to `build`, where bundling Clerk fails and the production
// server resolves a single react-router instance anyway.
...(command === 'serve' ? { ssr: { noExternal: ['@clerk/react-router'] } } : {}),
Comment on lines +12 to +18

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

Already talking to a react-router dev about this. There's an upstream issue in dev mode in v8 and to fix it, devs need to add @clerk/react-router to ssr.noExternal.

This should be handled upstream in the following releases. If we got any report of it for v8 users, we can instruct the fix

server: {
port: process.env.PORT ? Number(process.env.PORT) : undefined,
},
});
}));
80 changes: 80 additions & 0 deletions integration/tests/react-router/basic-v7.test.ts

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

v7 smoke test to make sure our package is backwards compat

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../../models/application';
import { appConfigs } from '../../presets';
import { createTestUtils } from '../../testUtils';

const reactRouterV7PackageJson = `{
"name": "clerk-react-router-quickstart",
"private": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "react-router dev --port $PORT",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"vite-tsconfig-paths": "^5.1.4"
}
}
`;

const reactRouterV7Config = `import type { Config } from '@react-router/dev/config';

export default {
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
`;

test.describe('React Router v7 compatibility @react-router', () => {
test.describe.configure({ mode: 'serial' });

let app: Application;

test.beforeAll(async () => {
app = await appConfigs.reactRouter.reactRouterNode
.clone()
.addFile('package.json', () => reactRouterV7PackageJson)
.addFile('react-router.config.ts', () => reactRouterV7Config)
.commit();

await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodes);
await app.dev();
});

test.afterAll(async () => {
await app?.teardown();
});

test('redirects unauthenticated protected route requests through v7 middleware context', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });

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

await expect(u.page).toHaveURL(`${app.serverUrl}/sign-in`);
await u.po.signIn.waitForMounted();
});
});
2 changes: 1 addition & 1 deletion packages/react-router/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@
"peerDependencies": {
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react",
"react-router": "^7.9.0"
"react-router": "^7.9.0 || ^8.0.0"
},
"engines": {
"node": ">=20.9.0"
Expand Down
9 changes: 2 additions & 7 deletions packages/react-router/src/server/clerkMiddleware.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,14 +25,9 @@ export const requestStateContext = createContext<RequestStateContextValue | null
* It checks the request's cookies and headers for a session JWT and, if found,
* attaches the Auth object to a context.
*
* @example
* // react-router.config.ts
* export default {
* future: {
* v8_middleware: true,
* },
* }
* If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
*
* @example
* // root.tsx
* export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
*/
Expand Down
19 changes: 13 additions & 6 deletions packages/react-router/src/server/utils.ts
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
import type { RequestState } from '@clerk/backend/internal';
import { constants, debugRequestState } from '@clerk/backend/internal';
import { parse as parseCookie } from 'cookie';
import type { AppLoadContext, UNSAFE_DataWithResponseInit } from 'react-router';
import type { UNSAFE_DataWithResponseInit } from 'react-router';

import { getPublicEnvVariables } from '../utils/env';
import { canUseKeyless } from '../utils/feature-flags';
import type { AdditionalStateOptions } from './types';

// AppLoadContext was removed from React Router v8. Keep a structural type for the context shape we use.
type ReactRouterContext = Record<string, any> & {
get?: <T>(context: unknown) => T | undefined;
set?: <T>(context: unknown, value: T) => void;
};

export function isResponse(value: any): value is Response {
return (
value != null &&
Expand DownExpand Up@@ -43,17 +49,18 @@ export function assertValidHandlerResult(val: any, error?: string): asserts val
}

/**
* `get` and `set` properties will only be available if v8_middleware flag is enabled
* See: https://reactrouter.com/upgrading/future#futurev8_middleware
* `get` and `set` properties are available when React Router middleware is enabled.
*/
export const IsOptIntoMiddleware = (context: AppLoadContext) => {
export const IsOptIntoMiddleware = (
context: ReactRouterContext,
): context is ReactRouterContext & Required<Pick<ReactRouterContext, 'get' | 'set'>> => {
return 'get' in context && 'set' in context;
};

export const injectRequestStateIntoResponse = async (
response: Response,
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
includeClerkHeaders = false,
) => {
Expand DownExpand Up@@ -82,7 +89,7 @@ export const injectRequestStateIntoResponse = async (
*/
export function getResponseClerkState(
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
) {
const { reason, message, isSignedIn, ...rest } = requestState;
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router/src/utils/env.ts
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
import { getEnvVariable } from '@clerk/shared/getEnvVariable';
import { isTruthy } from '@clerk/shared/underscore';
import type { AppLoadContext } from 'react-router';

export const getPublicEnvVariables = (context: AppLoadContext | undefined) => {
export const getPublicEnvVariables = (context: object | undefined) => {
const getValue = (name: string): string => {
return getEnvVariable(`VITE_${name}`, context) || getEnvVariable(name, context);
return (
getEnvVariable(`VITE_${name}`, context as Record<string, any>) ||
getEnvVariable(name, context as Record<string, any>)
);
};

return {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(react-router): Add support for React Router v8 by wobsoriano · Pull Request #8972 · clerk/javascript · GitHub
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
16 changes: 16 additions & 0 deletions .changeset/react-router-v8-support.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
---
'@clerk/react-router': minor
---

Add support for React Router v8.

If you're using React Router v7, keep the `v8_middleware` future flag enabled. If you're migrating to React Router v8, remove the flag:

```diff
// react-router.config.ts
export default {
- future: {
- v8_middleware: true,
- },
}
```
24 changes: 12 additions & 12 deletions integration/templates/react-router-node/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,20 +9,20 @@
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
"@react-router/node": "8.0.1",
"@react-router/serve": "8.0.1",
"isbot": "^5.1.36",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "8.0.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"@react-router/dev": "8.0.1",
"@types/node": "^22",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3",
"vite": "^8.0.3",
"vite-tsconfig-paths": "^5.1.4"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,4 @@ export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
11 changes: 9 additions & 2 deletions integration/templates/react-router-node/vite.config.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,21 @@ import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
export default defineConfig(({ command }) => ({
plugins: [
reactRouter(),
tsconfigPaths({
projects: ['./tsconfig.json'],
}),
],
// Dev-only: `react-router dev` externalizes @clerk/react-router for SSR, so Node
// loads it with a different react-router export condition (production) than Vite
// gives the app (development). That yields two react-router instances and breaks
// the Router context. noExternal routes Clerk through Vite so they share one
// instance. Not applied to `build`, where bundling Clerk fails and the production
// server resolves a single react-router instance anyway.
...(command === 'serve' ? { ssr: { noExternal: ['@clerk/react-router'] } } : {}),
Comment on lines +12 to +18

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

Already talking to a react-router dev about this. There's an upstream issue in dev mode in v8 and to fix it, devs need to add @clerk/react-router to ssr.noExternal.

This should be handled upstream in the following releases. If we got any report of it for v8 users, we can instruct the fix

server: {
port: process.env.PORT ? Number(process.env.PORT) : undefined,
},
});
}));
80 changes: 80 additions & 0 deletions integration/tests/react-router/basic-v7.test.ts

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

v7 smoke test to make sure our package is backwards compat

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../../models/application';
import { appConfigs } from '../../presets';
import { createTestUtils } from '../../testUtils';

const reactRouterV7PackageJson = `{
"name": "clerk-react-router-quickstart",
"private": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "react-router dev --port $PORT",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"vite-tsconfig-paths": "^5.1.4"
}
}
`;

const reactRouterV7Config = `import type { Config } from '@react-router/dev/config';

export default {
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
`;

test.describe('React Router v7 compatibility @react-router', () => {
test.describe.configure({ mode: 'serial' });

let app: Application;

test.beforeAll(async () => {
app = await appConfigs.reactRouter.reactRouterNode
.clone()
.addFile('package.json', () => reactRouterV7PackageJson)
.addFile('react-router.config.ts', () => reactRouterV7Config)
.commit();

await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodes);
await app.dev();
});

test.afterAll(async () => {
await app?.teardown();
});

test('redirects unauthenticated protected route requests through v7 middleware context', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });

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

await expect(u.page).toHaveURL(`${app.serverUrl}/sign-in`);
await u.po.signIn.waitForMounted();
});
});
2 changes: 1 addition & 1 deletion packages/react-router/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@
"peerDependencies": {
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react",
"react-router": "^7.9.0"
"react-router": "^7.9.0 || ^8.0.0"
},
"engines": {
"node": ">=20.9.0"
Expand Down
9 changes: 2 additions & 7 deletions packages/react-router/src/server/clerkMiddleware.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,14 +25,9 @@ export const requestStateContext = createContext<RequestStateContextValue | null
* It checks the request's cookies and headers for a session JWT and, if found,
* attaches the Auth object to a context.
*
* @example
* // react-router.config.ts
* export default {
* future: {
* v8_middleware: true,
* },
* }
* If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
*
* @example
* // root.tsx
* export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
*/
Expand Down
19 changes: 13 additions & 6 deletions packages/react-router/src/server/utils.ts
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
import type { RequestState } from '@clerk/backend/internal';
import { constants, debugRequestState } from '@clerk/backend/internal';
import { parse as parseCookie } from 'cookie';
import type { AppLoadContext, UNSAFE_DataWithResponseInit } from 'react-router';
import type { UNSAFE_DataWithResponseInit } from 'react-router';

import { getPublicEnvVariables } from '../utils/env';
import { canUseKeyless } from '../utils/feature-flags';
import type { AdditionalStateOptions } from './types';

// AppLoadContext was removed from React Router v8. Keep a structural type for the context shape we use.
type ReactRouterContext = Record<string, any> & {
get?: <T>(context: unknown) => T | undefined;
set?: <T>(context: unknown, value: T) => void;
};

export function isResponse(value: any): value is Response {
return (
value != null &&
Expand DownExpand Up@@ -43,17 +49,18 @@ export function assertValidHandlerResult(val: any, error?: string): asserts val
}

/**
* `get` and `set` properties will only be available if v8_middleware flag is enabled
* See: https://reactrouter.com/upgrading/future#futurev8_middleware
* `get` and `set` properties are available when React Router middleware is enabled.
*/
export const IsOptIntoMiddleware = (context: AppLoadContext) => {
export const IsOptIntoMiddleware = (
context: ReactRouterContext,
): context is ReactRouterContext & Required<Pick<ReactRouterContext, 'get' | 'set'>> => {
return 'get' in context && 'set' in context;
};

export const injectRequestStateIntoResponse = async (
response: Response,
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
includeClerkHeaders = false,
) => {
Expand DownExpand Up@@ -82,7 +89,7 @@ export const injectRequestStateIntoResponse = async (
*/
export function getResponseClerkState(
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
) {
const { reason, message, isSignedIn, ...rest } = requestState;
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router/src/utils/env.ts
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
import { getEnvVariable } from '@clerk/shared/getEnvVariable';
import { isTruthy } from '@clerk/shared/underscore';
import type { AppLoadContext } from 'react-router';

export const getPublicEnvVariables = (context: AppLoadContext | undefined) => {
export const getPublicEnvVariables = (context: object | undefined) => {
const getValue = (name: string): string => {
return getEnvVariable(`VITE_${name}`, context) || getEnvVariable(name, context);
return (
getEnvVariable(`VITE_${name}`, context as Record<string, any>) ||
getEnvVariable(name, context as Record<string, any>)
);
};

return {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(react-router): Add support for React Router v8 by wobsoriano · Pull Request #8972 · clerk/javascript · GitHub
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
16 changes: 16 additions & 0 deletions .changeset/react-router-v8-support.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
---
'@clerk/react-router': minor
---

Add support for React Router v8.

If you're using React Router v7, keep the `v8_middleware` future flag enabled. If you're migrating to React Router v8, remove the flag:

```diff
// react-router.config.ts
export default {
- future: {
- v8_middleware: true,
- },
}
```
24 changes: 12 additions & 12 deletions integration/templates/react-router-node/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,20 +9,20 @@
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
"@react-router/node": "8.0.1",
"@react-router/serve": "8.0.1",
"isbot": "^5.1.36",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "8.0.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"@react-router/dev": "8.0.1",
"@types/node": "^22",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3",
"vite": "^8.0.3",
"vite-tsconfig-paths": "^5.1.4"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,4 @@ export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
11 changes: 9 additions & 2 deletions integration/templates/react-router-node/vite.config.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,21 @@ import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
export default defineConfig(({ command }) => ({
plugins: [
reactRouter(),
tsconfigPaths({
projects: ['./tsconfig.json'],
}),
],
// Dev-only: `react-router dev` externalizes @clerk/react-router for SSR, so Node
// loads it with a different react-router export condition (production) than Vite
// gives the app (development). That yields two react-router instances and breaks
// the Router context. noExternal routes Clerk through Vite so they share one
// instance. Not applied to `build`, where bundling Clerk fails and the production
// server resolves a single react-router instance anyway.
...(command === 'serve' ? { ssr: { noExternal: ['@clerk/react-router'] } } : {}),
Comment on lines +12 to +18

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

Already talking to a react-router dev about this. There's an upstream issue in dev mode in v8 and to fix it, devs need to add @clerk/react-router to ssr.noExternal.

This should be handled upstream in the following releases. If we got any report of it for v8 users, we can instruct the fix

server: {
port: process.env.PORT ? Number(process.env.PORT) : undefined,
},
});
}));
80 changes: 80 additions & 0 deletions integration/tests/react-router/basic-v7.test.ts

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

v7 smoke test to make sure our package is backwards compat

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../../models/application';
import { appConfigs } from '../../presets';
import { createTestUtils } from '../../testUtils';

const reactRouterV7PackageJson = `{
"name": "clerk-react-router-quickstart",
"private": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "react-router dev --port $PORT",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"vite-tsconfig-paths": "^5.1.4"
}
}
`;

const reactRouterV7Config = `import type { Config } from '@react-router/dev/config';

export default {
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
`;

test.describe('React Router v7 compatibility @react-router', () => {
test.describe.configure({ mode: 'serial' });

let app: Application;

test.beforeAll(async () => {
app = await appConfigs.reactRouter.reactRouterNode
.clone()
.addFile('package.json', () => reactRouterV7PackageJson)
.addFile('react-router.config.ts', () => reactRouterV7Config)
.commit();

await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodes);
await app.dev();
});

test.afterAll(async () => {
await app?.teardown();
});

test('redirects unauthenticated protected route requests through v7 middleware context', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });

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

await expect(u.page).toHaveURL(`${app.serverUrl}/sign-in`);
await u.po.signIn.waitForMounted();
});
});
2 changes: 1 addition & 1 deletion packages/react-router/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@
"peerDependencies": {
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react",
"react-router": "^7.9.0"
"react-router": "^7.9.0 || ^8.0.0"
},
"engines": {
"node": ">=20.9.0"
Expand Down
9 changes: 2 additions & 7 deletions packages/react-router/src/server/clerkMiddleware.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,14 +25,9 @@ export const requestStateContext = createContext<RequestStateContextValue | null
* It checks the request's cookies and headers for a session JWT and, if found,
* attaches the Auth object to a context.
*
* @example
* // react-router.config.ts
* export default {
* future: {
* v8_middleware: true,
* },
* }
* If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
*
* @example
* // root.tsx
* export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
*/
Expand Down
19 changes: 13 additions & 6 deletions packages/react-router/src/server/utils.ts
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
import type { RequestState } from '@clerk/backend/internal';
import { constants, debugRequestState } from '@clerk/backend/internal';
import { parse as parseCookie } from 'cookie';
import type { AppLoadContext, UNSAFE_DataWithResponseInit } from 'react-router';
import type { UNSAFE_DataWithResponseInit } from 'react-router';

import { getPublicEnvVariables } from '../utils/env';
import { canUseKeyless } from '../utils/feature-flags';
import type { AdditionalStateOptions } from './types';

// AppLoadContext was removed from React Router v8. Keep a structural type for the context shape we use.
type ReactRouterContext = Record<string, any> & {
get?: <T>(context: unknown) => T | undefined;
set?: <T>(context: unknown, value: T) => void;
};

export function isResponse(value: any): value is Response {
return (
value != null &&
Expand DownExpand Up@@ -43,17 +49,18 @@ export function assertValidHandlerResult(val: any, error?: string): asserts val
}

/**
* `get` and `set` properties will only be available if v8_middleware flag is enabled
* See: https://reactrouter.com/upgrading/future#futurev8_middleware
* `get` and `set` properties are available when React Router middleware is enabled.
*/
export const IsOptIntoMiddleware = (context: AppLoadContext) => {
export const IsOptIntoMiddleware = (
context: ReactRouterContext,
): context is ReactRouterContext & Required<Pick<ReactRouterContext, 'get' | 'set'>> => {
return 'get' in context && 'set' in context;
};

export const injectRequestStateIntoResponse = async (
response: Response,
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
includeClerkHeaders = false,
) => {
Expand DownExpand Up@@ -82,7 +89,7 @@ export const injectRequestStateIntoResponse = async (
*/
export function getResponseClerkState(
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
) {
const { reason, message, isSignedIn, ...rest } = requestState;
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router/src/utils/env.ts
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
import { getEnvVariable } from '@clerk/shared/getEnvVariable';
import { isTruthy } from '@clerk/shared/underscore';
import type { AppLoadContext } from 'react-router';

export const getPublicEnvVariables = (context: AppLoadContext | undefined) => {
export const getPublicEnvVariables = (context: object | undefined) => {
const getValue = (name: string): string => {
return getEnvVariable(`VITE_${name}`, context) || getEnvVariable(name, context);
return (
getEnvVariable(`VITE_${name}`, context as Record<string, any>) ||
getEnvVariable(name, context as Record<string, any>)
);
};

return {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); feat(react-router): Add support for React Router v8 by wobsoriano · Pull Request #8972 · clerk/javascript · GitHub
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
16 changes: 16 additions & 0 deletions .changeset/react-router-v8-support.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
---
'@clerk/react-router': minor
---

Add support for React Router v8.

If you're using React Router v7, keep the `v8_middleware` future flag enabled. If you're migrating to React Router v8, remove the flag:

```diff
// react-router.config.ts
export default {
- future: {
- v8_middleware: true,
- },
}
```
24 changes: 12 additions & 12 deletions integration/templates/react-router-node/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,20 +9,20 @@
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
"@react-router/node": "8.0.1",
"@react-router/serve": "8.0.1",
"isbot": "^5.1.36",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-router": "8.0.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"@react-router/dev": "8.0.1",
"@types/node": "^22",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"typescript": "^5.9.3",
"vite": "^8.0.3",
"vite-tsconfig-paths": "^5.1.4"
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,8 +4,4 @@ export default {
// Config options...
// Server-side render by default, to enable SPA mode set this to `false`
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
11 changes: 9 additions & 2 deletions integration/templates/react-router-node/vite.config.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,14 +2,21 @@ import { reactRouter } from '@react-router/dev/vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
export default defineConfig(({ command }) => ({
plugins: [
reactRouter(),
tsconfigPaths({
projects: ['./tsconfig.json'],
}),
],
// Dev-only: `react-router dev` externalizes @clerk/react-router for SSR, so Node
// loads it with a different react-router export condition (production) than Vite
// gives the app (development). That yields two react-router instances and breaks
// the Router context. noExternal routes Clerk through Vite so they share one
// instance. Not applied to `build`, where bundling Clerk fails and the production
// server resolves a single react-router instance anyway.
...(command === 'serve' ? { ssr: { noExternal: ['@clerk/react-router'] } } : {}),
Comment on lines +12 to +18

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

Already talking to a react-router dev about this. There's an upstream issue in dev mode in v8 and to fix it, devs need to add @clerk/react-router to ssr.noExternal.

This should be handled upstream in the following releases. If we got any report of it for v8 users, we can instruct the fix

server: {
port: process.env.PORT ? Number(process.env.PORT) : undefined,
},
});
}));
80 changes: 80 additions & 0 deletions integration/tests/react-router/basic-v7.test.ts

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

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

v7 smoke test to make sure our package is backwards compat

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../../models/application';
import { appConfigs } from '../../presets';
import { createTestUtils } from '../../testUtils';

const reactRouterV7PackageJson = `{
"name": "clerk-react-router-quickstart",
"private": true,
"type": "module",
"scripts": {
"build": "react-router build",
"dev": "react-router dev --port $PORT",
"start": "NODE_ENV=production react-router-serve ./build/server/index.js",
"typecheck": "react-router typegen && tsc --build --noEmit"
},
"dependencies": {
"@react-router/node": "^7.9.1",
"@react-router/serve": "^7.9.1",
"isbot": "^5.1.17",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router": "^7.9.1"
},
"devDependencies": {
"@react-router/dev": "^7.9.1",
"@types/node": "^20",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"typescript": "^5.7.3",
"vite": "^7.1.5",
"vite-tsconfig-paths": "^5.1.4"
}
}
`;

const reactRouterV7Config = `import type { Config } from '@react-router/dev/config';

export default {
ssr: true,
future: {
v8_middleware: true,
unstable_optimizeDeps: true,
},
} satisfies Config;
`;

test.describe('React Router v7 compatibility @react-router', () => {
test.describe.configure({ mode: 'serial' });

let app: Application;

test.beforeAll(async () => {
app = await appConfigs.reactRouter.reactRouterNode
.clone()
.addFile('package.json', () => reactRouterV7PackageJson)
.addFile('react-router.config.ts', () => reactRouterV7Config)
.commit();

await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodes);
await app.dev();
});

test.afterAll(async () => {
await app?.teardown();
});

test('redirects unauthenticated protected route requests through v7 middleware context', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });

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

await expect(u.page).toHaveURL(`${app.serverUrl}/sign-in`);
await u.po.signIn.waitForMounted();
});
});
2 changes: 1 addition & 1 deletion packages/react-router/package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,7 +110,7 @@
"peerDependencies": {
"react": "catalog:peer-react",
"react-dom": "catalog:peer-react",
"react-router": "^7.9.0"
"react-router": "^7.9.0 || ^8.0.0"
},
"engines": {
"node": ">=20.9.0"
Expand Down
9 changes: 2 additions & 7 deletions packages/react-router/src/server/clerkMiddleware.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,14 +25,9 @@ export const requestStateContext = createContext<RequestStateContextValue | null
* It checks the request's cookies and headers for a session JWT and, if found,
* attaches the Auth object to a context.
*
* @example
* // react-router.config.ts
* export default {
* future: {
* v8_middleware: true,
* },
* }
* If you're using React Router v7, enable the v8_middleware future flag in your react-router.config.ts file.
*
* @example
* // root.tsx
* export const middleware: Route.MiddlewareFunction[] = [clerkMiddleware()]
*/
Expand Down
19 changes: 13 additions & 6 deletions packages/react-router/src/server/utils.ts
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
import type { RequestState } from '@clerk/backend/internal';
import { constants, debugRequestState } from '@clerk/backend/internal';
import { parse as parseCookie } from 'cookie';
import type { AppLoadContext, UNSAFE_DataWithResponseInit } from 'react-router';
import type { UNSAFE_DataWithResponseInit } from 'react-router';

import { getPublicEnvVariables } from '../utils/env';
import { canUseKeyless } from '../utils/feature-flags';
import type { AdditionalStateOptions } from './types';

// AppLoadContext was removed from React Router v8. Keep a structural type for the context shape we use.
type ReactRouterContext = Record<string, any> & {
get?: <T>(context: unknown) => T | undefined;
set?: <T>(context: unknown, value: T) => void;
};

export function isResponse(value: any): value is Response {
return (
value != null &&
Expand DownExpand Up@@ -43,17 +49,18 @@ export function assertValidHandlerResult(val: any, error?: string): asserts val
}

/**
* `get` and `set` properties will only be available if v8_middleware flag is enabled
* See: https://reactrouter.com/upgrading/future#futurev8_middleware
* `get` and `set` properties are available when React Router middleware is enabled.
*/
export const IsOptIntoMiddleware = (context: AppLoadContext) => {
export const IsOptIntoMiddleware = (
context: ReactRouterContext,
): context is ReactRouterContext & Required<Pick<ReactRouterContext, 'get' | 'set'>> => {
return 'get' in context && 'set' in context;
};

export const injectRequestStateIntoResponse = async (
response: Response,
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
includeClerkHeaders = false,
) => {
Expand DownExpand Up@@ -82,7 +89,7 @@ export const injectRequestStateIntoResponse = async (
*/
export function getResponseClerkState(
requestState: RequestState,
context: AppLoadContext,
context: ReactRouterContext,
additionalStateOptions: AdditionalStateOptions = {},
) {
const { reason, message, isSignedIn, ...rest } = requestState;
Expand Down
8 changes: 5 additions & 3 deletions packages/react-router/src/utils/env.ts
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
import { getEnvVariable } from '@clerk/shared/getEnvVariable';
import { isTruthy } from '@clerk/shared/underscore';
import type { AppLoadContext } from 'react-router';

export const getPublicEnvVariables = (context: AppLoadContext | undefined) => {
export const getPublicEnvVariables = (context: object | undefined) => {
const getValue = (name: string): string => {
return getEnvVariable(`VITE_${name}`, context) || getEnvVariable(name, context);
return (
getEnvVariable(`VITE_${name}`, context as Record<string, any>) ||
getEnvVariable(name, context as Record<string, any>)
);
};

return {
Expand Down
Loading