-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathclerkClient.ts
More file actions
39 lines (33 loc) · 1.38 KB
/
clerkClient.ts
File metadata and controls
39 lines (33 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { constants } from '@clerk/backend/internal';
import { buildRequestLike, isNextjsUseCacheError, isPrerenderingBailout } from '../app-router/server/utils';
import { createClerkClientWithOptions } from './createClerkClient';
import { getHeader } from './headers-utils';
import { clerkMiddlewareRequestDataStorage } from './middleware-storage';
import { decryptClerkRequestData } from './utils';
/**
* Constructs a BAPI client that accesses request data within the runtime.
* Necessary if middleware dynamic keys are used.
*/
const clerkClient = async () => {
let requestData;
try {
const request = await buildRequestLike();
const encryptedRequestData = getHeader(request, constants.Headers.ClerkRequestData);
requestData = decryptClerkRequestData(encryptedRequestData);
} catch (err) {
if (err && isPrerenderingBailout(err)) {
throw err;
}
// Re-throw "use cache" errors with the helpful message from buildRequestLike
if (err && isNextjsUseCacheError(err)) {
throw err;
}
}
// Fallbacks between options from middleware runtime and `NextRequest` from application server
const options = clerkMiddlewareRequestDataStorage.getStore()?.get('requestData') ?? requestData;
if (options?.secretKey || options?.publishableKey) {
return createClerkClientWithOptions(options);
}
return createClerkClientWithOptions({});
};
export { clerkClient };