Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add react-router SDK #4621

Draft
wants to merge 29 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
f414fcc
add modified react-router playground app
LekoArts Nov 21, 2024
cc77f7d
add initial (unmodified) react-router pkg
LekoArts Nov 21, 2024
b0df0a1
get playground working
LekoArts Nov 21, 2024
7fbc46a
more playground updates
LekoArts Nov 21, 2024
bcd5231
run codemod on playground for react-router
LekoArts Nov 21, 2024
349b892
use new package
LekoArts Nov 21, 2024
4540b05
update imports
LekoArts Nov 22, 2024
4e3a4df
fix(react-router): Update playground & pkg (#4628)
wobsoriano Nov 22, 2024
f538061
remove workspace usage used for debugging
LekoArts Nov 22, 2024
dfb3807
add name
LekoArts Nov 22, 2024
dcc22e4
add changeset
LekoArts Nov 22, 2024
91c2a5f
remove unused files
LekoArts Nov 22, 2024
de98050
remove unused script
LekoArts Nov 22, 2024
74fabec
make pkg ESM-only
LekoArts Nov 22, 2024
ead6304
update some remix => react-router instances
LekoArts Nov 22, 2024
2c53767
fix build artifacts
LekoArts Nov 22, 2024
885a9b1
update eslint
LekoArts Nov 22, 2024
bd67155
fix routerData
LekoArts Nov 22, 2024
fc2ddc3
use declarative routes instead of fs
LekoArts Nov 22, 2024
2b9d829
fix types
LekoArts Nov 22, 2024
ef306a6
update packages
LekoArts Nov 25, 2024
94e4944
Merge branch 'main' into lekoarts/eco-247-bootstrap-new-package
LekoArts Nov 25, 2024
a033b66
update tsup config
LekoArts Nov 25, 2024
62b7c8e
Use ClerkProvider instead of HoC
LekoArts Nov 25, 2024
57c6675
maybe now correct tsup config?
LekoArts Nov 25, 2024
e5a070c
cleanup
LekoArts Nov 26, 2024
b8b615c
yey, RR fix
LekoArts Dec 3, 2024
13fa112
Merge branch 'main' into lekoarts/eco-247-bootstrap-new-package
LekoArts Dec 3, 2024
700f48e
improve types
LekoArts Dec 3, 2024
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
5 changes: 5 additions & 0 deletions .changeset/clean-pigs-hope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/react-router': patch
---

Initial beta release of `@clerk/react-router`. TODO
4 changes: 4 additions & 0 deletions packages/react-router/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: ['@clerk/custom/browser', '@clerk/custom/typescript', '@clerk/custom/jest', '@clerk/custom/react'],
};
1 change: 1 addition & 0 deletions packages/react-router/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Change Log
21 changes: 21 additions & 0 deletions packages/react-router/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Clerk, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
72 changes: 72 additions & 0 deletions packages/react-router/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<p align="center">
<a href="https://clerk.com?utm_source=github&utm_medium=clerk_react-router" target="_blank" rel="noopener noreferrer">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://images.clerk.com/static/logo-dark-mode-400x400.png">
<img src="https://images.clerk.com/static/logo-light-mode-400x400.png" height="64">
</picture>
</a>
<br />
<h1 align="center">@clerk/react-router</h1>
</p>

<div align="center">

[![Chat on Discord](https://img.shields.io/discord/856971667393609759.svg?logo=discord)](https://clerk.com/discord)
[![Clerk documentation](https://img.shields.io/badge/documentation-clerk-green.svg)](https://clerk.com/docs?utm_source=github&utm_medium=clerk_react-router)
[![Follow on Twitter](https://img.shields.io/twitter/follow/ClerkDev?style=social)](https://twitter.com/intent/follow?screen_name=ClerkDev)

[Changelog](https://github.com/clerk/javascript/blob/main/packages/react-router/CHANGELOG.md)
·
[Report a Bug](https://github.com/clerk/javascript/issues/new?assignees=&labels=needs-triage&projects=&template=BUG_REPORT.yml)
·
[Request a Feature](https://feedback.clerk.com/roadmap)
·
[Get help](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_react-router)

</div>

## Getting Started

[Clerk](https://clerk.com/?utm_source=github&utm_medium=clerk_react-router) is the easiest way to add authentication and user management to your Remix application. Add sign up, sign in, and profile management to your application in minutes.

### Prerequisites

- React Router `^7.0.0` or later
- React 18 or later
- Node.js `>=20.0.0` or later
- An existing Clerk application. [Create your account for free](https://dashboard.clerk.com/sign-up?utm_source=github&utm_medium=clerk_react-router).

### Installation

The fastest way to get started with Clerk is by following the [Remix Quickstart](https://clerk.com/docs/quickstarts/remix?utm_source=github&utm_medium=clerk_react-router).

You'll learn how to install `@clerk/react-router`, set up your environment keys, configure `rootAuthLoader` & `ClerkApp`, and protect your pages.

## Usage

For further information, guides, and examples visit the [Remix reference documentation](https://clerk.com/docs/references/remix/clerk-app?utm_source=github&utm_medium=clerk_react-router).

## Support

You can get in touch with us in any of the following ways:

- Join our official community [Discord server](https://clerk.com/discord)
- On [our support page](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_react-router)

## Contributing

We're open to all community contributions! If you'd like to contribute in any way, please read [our contribution guidelines](https://github.com/clerk/javascript/blob/main/docs/CONTRIBUTING.md) and [code of conduct](https://github.com/clerk/javascript/blob/main/docs/CODE_OF_CONDUCT.md).

## Security

`@clerk/react-router` follows good practices of security, but 100% security cannot be assured.

`@clerk/react-router` is provided **"as is"** without any **warranty**. Use at your own risk.

_For more information and to report security issues, please refer to our [security documentation](https://github.com/clerk/javascript/blob/main/docs/SECURITY.md)._

## License

This project is licensed under the **MIT license**.

See [LICENSE](https://github.com/clerk/javascript/blob/main/packages/react-router/LICENSE) for more information.
102 changes: 102 additions & 0 deletions packages/react-router/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
{
"name": "@clerk/react-router",
"version": "0.0.0",
"description": "Clerk SDK for React Router",
"keywords": [
"clerk",
"typescript",
"react-router",
"auth",
"authentication",
"passwordless",
"session",
"jwt"
],
"homepage": "https://clerk.com/",
"bugs": {
"url": "https://github.com/clerk/javascript/issues"
},
"repository": {
"type": "git",
"url": "git+https://github.com/clerk/javascript.git",
"directory": "packages/react-router"
},
"license": "MIT",
"author": "Clerk",
"sideEffects": false,
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./ssr.server": {
"types": "./dist/ssr/index.d.ts",
"import": "./dist/ssr/index.js"
},
"./api.server": {
"types": "./dist/api/index.d.ts",
"import": "./dist/api/index.js"
},
"./errors": {
"types": "./dist/errors.d.ts",
"import": "./dist/errors.js"
}
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"typesVersions": {
"*": {
"*": [
"dist/*.d.ts",
"dist/index.d.ts"
],
"ssr.server": [
"dist/ssr/index.d.ts"
],
"api.server": [
"dist/api/index.d.ts"
]
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"lint": "eslint src/",
"lint:attw": "attw --pack .",
"lint:publint": "publint",
"publish:local": "pnpm dlx yalc push --replace --sig"
},
"dependencies": {
"@clerk/backend": "workspace:*",
"@clerk/clerk-react": "workspace:*",
"@clerk/shared": "workspace:*",
"@clerk/types": "workspace:*",
"cookie": "0.7.0",
"tslib": "catalog:repo"
},
"devDependencies": {
"@clerk/eslint-config-custom": "workspace:*",
"@types/cookie": "^0.6.0",
"@types/node": "^18.19.33",
"@types/react": "catalog:react",
"@types/react-dom": "catalog:react",
"esbuild-plugin-file-path-extensions": "^2.1.3",
"react-router": "7.0.2",
"typescript": "catalog:repo"
},
"peerDependencies": {
"react": ">=18",
"react-dom": ">=18",
"react-router": "^7.0.2"
},
"engines": {
"node": ">=20.0.0"
},
"publishConfig": {
"access": "public"
}
}
1 change: 1 addition & 0 deletions packages/react-router/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from '@clerk/backend';
150 changes: 150 additions & 0 deletions packages/react-router/src/client/ReactRouterClerkProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { ClerkProvider as ReactClerkProvider } from '@clerk/clerk-react';
import React from 'react';

import { assertPublishableKeyInSpaMode, assertValidClerkState, inSpaMode, warnForSsr } from '../utils';
import { ClerkReactRouterOptionsProvider } from './ReactRouterOptionsContext';
import type { ClerkState, ReactRouterClerkProviderProps, ReactRouterComponentProps } from './types';
import { useAwaitableNavigate } from './useAwaitableNavigate';

export * from '@clerk/clerk-react';

const SDK_METADATA = {
name: PACKAGE_NAME,
version: PACKAGE_VERSION,
};

/**
* Remix hydration errors should not stop Clerk navigation from working, as the components mount only after
* hydration is done (in the case of a hydration error, the components will simply mount after client-side hydration)
* In the case of a hydration error, the first `navigate` function we get from the `useNavigate` hook will not work
* because the RemixClerkProvider (which is part of the host app) will unmount before the following useEffect within `navigate` fires:
* https://github.com/remix-run/react-router/blob/main/packages/react-router/lib/hooks.tsx#L175
* so isomorphicClerk will initialize with a `navigate` function that will never have `activeRef.current` set to true.
* This variable is just an object ref/cache outside the React rendering cycle that holds a reference to the
* latest `navigate` function. After a hydration error occurs, RemixClerkProvider will *remount* and this variable
* will finally get a `navigate` function that has a `activeRef.current` to true so navigation will function as it should.
*/
const awaitableNavigateRef: { current: ReturnType<typeof useAwaitableNavigate> | undefined } = { current: undefined };

/**
* Internal type that includes the initial state prop that is passed to the ClerkProvider during SSR.
* This is a value that we pass automatically so it does not need to pollute the public API.
*/
type ClerkProviderPropsWithState = ReactRouterClerkProviderProps & {
clerkState?: ClerkState;
};

function ClerkProviderBase({ children, ...rest }: ClerkProviderPropsWithState): JSX.Element {
const awaitableNavigate = useAwaitableNavigate();
const isSpaMode = inSpaMode();

React.useEffect(() => {
awaitableNavigateRef.current = awaitableNavigate;
}, [awaitableNavigate]);

const { clerkState, ...restProps } = rest;
ReactClerkProvider.displayName = 'ReactClerkProvider';

if (!isSpaMode) {
assertValidClerkState(clerkState);
}

const {
__clerk_ssr_state,
__publishableKey,
__proxyUrl,
__domain,
__isSatellite,
__clerk_debug,
__signInUrl,
__signUpUrl,
__afterSignInUrl,
__afterSignUpUrl,
__signInForceRedirectUrl,
__signUpForceRedirectUrl,
__signInFallbackRedirectUrl,
__signUpFallbackRedirectUrl,
__clerkJSUrl,
__clerkJSVersion,
__telemetryDisabled,
__telemetryDebug,
} = clerkState?.__internal_clerk_state || {};

React.useEffect(() => {
if (!isSpaMode) {
warnForSsr(clerkState);
}
}, []);

React.useEffect(() => {
(window as any).__clerk_debug = __clerk_debug;
}, []);

const mergedProps = {
publishableKey: __publishableKey as any,
proxyUrl: __proxyUrl as any,
domain: __domain as any,
isSatellite: __isSatellite,
signInUrl: __signInUrl,
signUpUrl: __signUpUrl,
afterSignInUrl: __afterSignInUrl,
afterSignUpUrl: __afterSignUpUrl,
signInForceRedirectUrl: __signInForceRedirectUrl,
signUpForceRedirectUrl: __signUpForceRedirectUrl,
signInFallbackRedirectUrl: __signInFallbackRedirectUrl,
signUpFallbackRedirectUrl: __signUpFallbackRedirectUrl,
clerkJSUrl: __clerkJSUrl,
clerkJSVersion: __clerkJSVersion,
telemetry: {
disabled: __telemetryDisabled,
debug: __telemetryDebug,
},
};

return (
<ClerkReactRouterOptionsProvider options={mergedProps}>
<ReactClerkProvider
routerPush={(to: string) => awaitableNavigateRef.current?.(to)}
routerReplace={(to: string) => awaitableNavigateRef.current?.(to, { replace: true })}
initialState={__clerk_ssr_state}
sdkMetadata={SDK_METADATA}
{...mergedProps}
{...restProps}
>
{children}
</ReactClerkProvider>
</ClerkReactRouterOptionsProvider>
);
}

type ClerkReactRouterOptions = Partial<
Omit<ReactRouterClerkProviderProps, 'routerPush' | 'routerReplace' | 'clerkState'>
>;

// TODO: Remove "any" on loaderData type
type ClerkProviderProps = ClerkReactRouterOptions & {
loaderData: ReactRouterComponentProps['loaderData'];
};

export const ClerkProvider = ({ children, loaderData, ...opts }: ClerkProviderProps) => {
let clerkState;
const isSpaMode = inSpaMode();

// Don't use `loaderData` to fetch the clerk state if we're in SPA mode
if (!isSpaMode) {
clerkState = loaderData.clerkState;
}

if (isSpaMode) {
assertPublishableKeyInSpaMode(opts.publishableKey);
}

return (
<ClerkProviderBase
{...(opts as ReactRouterClerkProviderProps)}
clerkState={clerkState}
>
{children}
</ClerkProviderBase>
);
};
22 changes: 22 additions & 0 deletions packages/react-router/src/client/ReactRouterOptionsContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import React from 'react';

import type { ReactRouterClerkProviderProps } from './types';

type ClerkReactRouterContextValue = Partial<Omit<ReactRouterClerkProviderProps, 'children'>>;

const ClerkReactRouterOptionsCtx = React.createContext<{ value: ClerkReactRouterContextValue } | undefined>(undefined);
ClerkReactRouterOptionsCtx.displayName = 'ClerkReactRouterOptionsCtx';

const useClerkReactRouterOptions = (): ClerkReactRouterContextValue => {
const ctx = React.useContext(ClerkReactRouterOptionsCtx) as { value: ClerkReactRouterContextValue };
return ctx.value;
};

const ClerkReactRouterOptionsProvider = (props: React.PropsWithChildren<{ options: ClerkReactRouterContextValue }>) => {
const { children, options } = props;
return (
<ClerkReactRouterOptionsCtx.Provider value={{ value: options }}>{children}</ClerkReactRouterOptionsCtx.Provider>
);
};

export { ClerkReactRouterOptionsProvider, useClerkReactRouterOptions };
3 changes: 3 additions & 0 deletions packages/react-router/src/client/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './ReactRouterClerkProvider';
export type { WithClerkState } from './types';
export { SignIn, SignUp } from './uiComponents';
Loading
Loading