-
Notifications
You must be signed in to change notification settings - Fork 361
feat(nextjs): Support Keyless mode #4602
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
Changes from 24 commits
202e089
ef1e29a
55e1f2d
86758da
af91677
0b40c97
0646cc9
5e0181d
07d7a08
dbfb097
7f0020a
293b15b
e971a2d
c4b1ac5
afd7dc9
8e1b64f
ca1df30
41bc200
b27445d
29abac2
92efadc
5342e15
b594ace
0888c61
eded662
fd12da6
bc7fc4c
1b203ae
b2bad5e
c0210e1
8df06f3
06c1f73
2950e68
206bb4f
b04a9d2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
--- | ||
'@clerk/clerk-js': minor | ||
'@clerk/types': minor | ||
--- | ||
|
||
accountless | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Once we're ready, let's expand the changeset description here. And consolidate the two changeset files. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
--- | ||
'@clerk/backend': minor | ||
'@clerk/nextjs': minor | ||
--- | ||
|
||
accountless | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. todo |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -132,7 +132,7 @@ export default function RootLayout({ children }: { children: React.ReactNode }) | |
'src/app/nested-provider/page.tsx', | ||
() => `import { ClerkProvider } from '@clerk/nextjs'; | ||
import { ClientComponent } from './client'; | ||
|
||
export default function Page() { | ||
return ( | ||
<ClerkProvider dynamic> | ||
|
@@ -147,10 +147,10 @@ export default function RootLayout({ children }: { children: React.ReactNode }) | |
() => `'use client'; | ||
|
||
import { useAuth } from '@clerk/nextjs'; | ||
|
||
export function ClientComponent() { | ||
useAuth(); | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is just auto formatting |
||
return <p>I am dynamically rendered</p>; | ||
} | ||
`, | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import type { AccountlessApplication } from '../resources/AccountlessApplication'; | ||
import { AbstractAPI } from './AbstractApi'; | ||
|
||
const basePath = '/accountless_applications'; | ||
|
||
export class AccountlessApplicationAPI extends AbstractAPI { | ||
public async createAccountlessApplication() { | ||
return this.request<AccountlessApplication>({ | ||
method: 'POST', | ||
path: basePath, | ||
}); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
import { | ||
AccountlessApplicationAPI, | ||
AllowlistIdentifierAPI, | ||
ClientAPI, | ||
DomainAPI, | ||
|
@@ -23,6 +24,9 @@ export function createBackendApiClient(options: CreateBackendApiOptions) { | |
const request = buildRequest(options); | ||
|
||
return { | ||
__experimental_accountlessApplications: new AccountlessApplicationAPI( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i'd like to have this as experimental for a while |
||
buildRequest({ ...options, requireSecretKey: false }), | ||
), | ||
allowlistIdentifiers: new AllowlistIdentifierAPI(request), | ||
clients: new ClientAPI(request), | ||
emailAddresses: new EmailAddressAPI(request), | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import type { AccountlessApplicationJSON } from './JSON'; | ||
|
||
export class AccountlessApplication { | ||
constructor( | ||
readonly publishableKey: string, | ||
readonly secretKey: string, | ||
readonly claimUrl: string, | ||
) {} | ||
|
||
static fromJSON(data: AccountlessApplicationJSON): AccountlessApplication { | ||
return new AccountlessApplication(data.publishable_key, data.secret_key, data.claim_url); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
'use server'; | ||
import type { AccountlessApplication } from '@clerk/backend'; | ||
import { getCookies } from 'ezheaders'; | ||
import { redirect, RedirectType } from 'next/navigation'; | ||
|
||
import { getKeylessCookieName } from '../server/accountless'; | ||
import { canUseKeyless__server } from '../utils/feature-flags'; | ||
|
||
export async function syncKeylessConfigAction(args: AccountlessApplication & { returnUrl: string }): Promise<void> { | ||
const { claimUrl, publishableKey, secretKey, returnUrl } = args; | ||
void (await getCookies()).set(getKeylessCookieName(), JSON.stringify({ claimUrl, publishableKey, secretKey }), { | ||
secure: true, | ||
httpOnly: true, | ||
}); | ||
|
||
// TODO-ACCOUNTLESS: Do we even need this ? I think setting the cookie will reset the router cache. | ||
redirect(`/clerk-sync-keyless?returnUrl=${returnUrl}`, RedirectType.replace); | ||
} | ||
|
||
export async function createKeylessApplicationAction(): Promise<null | Omit<AccountlessApplication, 'secretKey'>> { | ||
if (!canUseKeyless__server) { | ||
return null; | ||
} | ||
|
||
const result = await import('../server/accountless-node.js').then(m => m.createOrReadKeyless()); | ||
|
||
if (!result) { | ||
return null; | ||
} | ||
|
||
const { claimUrl, publishableKey, secretKey } = result; | ||
|
||
void (await getCookies()).set(getKeylessCookieName(), JSON.stringify({ claimUrl, publishableKey, secretKey }), { | ||
secure: false, | ||
httpOnly: false, | ||
}); | ||
|
||
return { | ||
claimUrl, | ||
publishableKey, | ||
}; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,6 +2,7 @@ | |
import { ClerkProvider as ReactClerkProvider } from '@clerk/clerk-react'; | ||
import { inBrowser } from '@clerk/shared/browser'; | ||
import { logger } from '@clerk/shared/logger'; | ||
import dynamic from 'next/dynamic'; | ||
import { useRouter } from 'next/navigation'; | ||
import nextPackage from 'next/package.json'; | ||
import React, { useEffect, useTransition } from 'react'; | ||
|
@@ -10,11 +11,21 @@ import { useSafeLayoutEffect } from '../../client-boundary/hooks/useSafeLayoutEf | |
import { ClerkNextOptionsProvider, useClerkNextOptions } from '../../client-boundary/NextOptionsContext'; | ||
import type { NextClerkProviderProps } from '../../types'; | ||
import { ClerkJSScript } from '../../utils/clerk-js-script'; | ||
import { canUseKeyless__client } from '../../utils/feature-flags'; | ||
import { mergeNextClerkPropsWithEnv } from '../../utils/mergeNextClerkPropsWithEnv'; | ||
import { isNextWithUnstableServerActions } from '../../utils/sdk-versions'; | ||
import { invalidateCacheAction } from '../server-actions'; | ||
import { useAwaitablePush } from './useAwaitablePush'; | ||
import { useAwaitableReplace } from './useAwaitableReplace'; | ||
|
||
/** | ||
* Accountless creator should only be loaded if the conditions below are met. | ||
* Note: Using lazy() with Suspense instead of dynamic is not possible as React will throw a hydration error when `ClerkProvider` wraps `<html><body>...` | ||
*/ | ||
const LazyCreateKeylessApplication = dynamic(() => | ||
import('./lazy-accountless-creator.js').then(m => m.CreateKeylessApplication), | ||
); | ||
|
||
declare global { | ||
export interface Window { | ||
__clerk_nav_await: Array<(value: void) => void>; | ||
|
@@ -26,10 +37,8 @@ declare global { | |
} | ||
} | ||
|
||
const isDeprecatedNextjsVersion = nextPackage.version.startsWith('13.') || nextPackage.version.startsWith('14.0'); | ||
|
||
export const ClientClerkProvider = (props: NextClerkProviderProps) => { | ||
if (isDeprecatedNextjsVersion) { | ||
const NextClientClerkProvider = (props: NextClerkProviderProps) => { | ||
if (isNextWithUnstableServerActions) { | ||
const deprecationWarning = `Clerk:\nYour current Next.js version (${nextPackage.version}) will be deprecated in the next major release of "@clerk/nextjs". Please upgrade to [email protected] or later.`; | ||
if (inBrowser()) { | ||
logger.warnOnce(deprecationWarning); | ||
|
@@ -113,3 +122,18 @@ export const ClientClerkProvider = (props: NextClerkProviderProps) => { | |
</ClerkNextOptionsProvider> | ||
); | ||
}; | ||
|
||
export const ClientClerkProvider = (props: NextClerkProviderProps) => { | ||
const { children, ...rest } = props; | ||
const safePublishableKey = mergeNextClerkPropsWithEnv(rest).publishableKey; | ||
|
||
if (safePublishableKey || !canUseKeyless__client) { | ||
return <NextClientClerkProvider {...rest}>{children}</NextClientClerkProvider>; | ||
} | ||
|
||
return ( | ||
<LazyCreateKeylessApplication> | ||
<NextClientClerkProvider {...rest}>{children}</NextClientClerkProvider> | ||
</LazyCreateKeylessApplication> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
'use client'; | ||
|
||
import type { AccountlessApplication } from '@clerk/backend'; | ||
import type { PropsWithChildren } from 'react'; | ||
import { useEffect } from 'react'; | ||
|
||
import { canUseKeyless__client } from '../../utils/feature-flags'; | ||
|
||
export function KeylessCookieSync(props: PropsWithChildren<AccountlessApplication>) { | ||
useEffect(() => { | ||
if (canUseKeyless__client) { | ||
void import('../accountless-actions.js').then(m => | ||
m.syncKeylessConfigAction({ | ||
...props, | ||
// Preserve the current url and return back, once keys are synced in the middleware | ||
returnUrl: window.location.href, | ||
}), | ||
); | ||
} | ||
}, []); | ||
|
||
return props.children; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import React, { useEffect } from 'react'; | ||
|
||
import type { NextClerkProviderProps } from '../../types'; | ||
import { createKeylessApplicationAction } from '../accountless-actions'; | ||
|
||
export const CreateKeylessApplication = (props: NextClerkProviderProps) => { | ||
const { children } = props; | ||
const [state, fetchKeys] = React.useActionState(createKeylessApplicationAction, null); | ||
useEffect(() => { | ||
React.startTransition(() => { | ||
fetchKeys(); | ||
}); | ||
}, []); | ||
|
||
if (!React.isValidElement(children)) { | ||
return children; | ||
} | ||
|
||
return React.cloneElement(children, { | ||
key: state?.publishableKey, | ||
publishableKey: state?.publishableKey, | ||
__internal_claimKeylessApplicationUrl: state?.claimUrl, | ||
__internal_bypassMissingPublishableKey: true, | ||
} as any); | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
todo