-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathpage.tsx
More file actions
77 lines (68 loc) · 2.5 KB
/
page.tsx
File metadata and controls
77 lines (68 loc) · 2.5 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { init } from '@launchdarkly/node-server-sdk';
import { createLDServerSession, LDIsomorphicProvider } from '@launchdarkly/react-sdk/server';
import App from './App';
// The base client is a module-level singleton — initialized once for the lifetime of the
// Node.js process and shared across all incoming requests.
const sdkKey = process.env.LAUNCHDARKLY_SDK_KEY || '';
const clientSideId = process.env.LAUNCHDARKLY_CLIENT_SIDE_ID || '';
const ldBaseClient = sdkKey ? init(sdkKey) : null;
// Select via ?context=sandy|jamie|alex (defaults to sandy).
const PRESET_CONTEXTS = {
sandy: { kind: 'user' as const, key: 'example-user-key', name: 'Sandy' },
jamie: { kind: 'user' as const, key: 'user-jamie', name: 'Jamie' },
alex: { kind: 'user' as const, key: 'user-alex', name: 'Alex' },
};
export default async function Home({
searchParams,
}: {
searchParams: Promise<{ context?: string }>;
}) {
if (!ldBaseClient) {
return (
<div className="error">
<p>
LaunchDarkly SDK key is required: set the LAUNCHDARKLY_SDK_KEY environment variable and
try again.
</p>
</div>
);
}
if (!clientSideId) {
return (
<div className="error">
<p>
LaunchDarkly client-side ID is required: set the LAUNCHDARKLY_CLIENT_SIDE_ID environment
variable and try again.
</p>
</div>
);
}
try {
await ldBaseClient.waitForInitialization({ timeout: 10 });
} catch {
return (
<div className="error">
<p>
SDK failed to initialize. Please check your internet connection and SDK credential for any
typo.
</p>
</div>
);
}
// Resolve the evaluation context from the ?context= query parameter.
// In a real app this would come from authentication tokens, cookies, or session data.
const { context: contextKey = 'sandy' } = await searchParams;
const context =
PRESET_CONTEXTS[contextKey as keyof typeof PRESET_CONTEXTS] ?? PRESET_CONTEXTS.sandy;
// Create a per-request session bound to this user's context.
// createLDServerSession also stores the session in React's cache() so any Server Component
// in this render tree can retrieve it via useLDServerSession().
const session = createLDServerSession(ldBaseClient, context);
// Wrap the app with LDIsomorphicProvider to bootstrap the browser SDK with
// server-evaluated flag values.
return (
<LDIsomorphicProvider session={session} clientSideId={clientSideId}>
<App />
</LDIsomorphicProvider>
);
}