UNPKG

@devcycle/nextjs-sdk

Version:

The Next.js SDK for DevCycle!

72 lines 2.79 kB
import { initializeDevCycle, } from '@devcycle/js-client-sdk'; import { getUserAgent } from './userAgent'; import { cache } from 'react'; import { getBucketedConfig, getConfigFromSource } from './bucketing'; import { cookies } from 'next/headers'; import { debugUserCookieName } from '../common/cookie'; const jsClientOptions = { // pass next object to enable "next" mode in JS SDK next: { disableAutomaticEventFlush: true }, disableConfigCache: true, disableRealtimeUpdates: true, sdkPlatform: 'nextjs', }; const getWebDebugUser = async () => { try { // Check for user debug cookie const cookieStore = await cookies(); const userCookie = cookieStore.get(debugUserCookieName); if (userCookie === null || userCookie === void 0 ? void 0 : userCookie.value) { return JSON.parse(userCookie.value); } } catch (error) { console.warn('Failed to parse DevCycle user cookie:', error); } return null; }; const cachedUserGetter = cache(async (userGetter, options) => { // If static mode is enabled, use the userGetter directly if (options.staticMode) { return userGetter(); } const webDebugUser = await getWebDebugUser(); // Fallback to original userGetter return webDebugUser !== null && webDebugUser !== void 0 ? webDebugUser : userGetter(); }); export const initialize = cache(async (sdkKey, clientSDKKey, userGetter, options = {}) => { const [userAgent, user, configData] = await Promise.all([ getUserAgent(options), cachedUserGetter(userGetter, options), getConfigFromSource(sdkKey, clientSDKKey, options), ]); if (!user || typeof user.user_id !== 'string') { throw new Error('DevCycle user getter must return a user'); } const client = initializeDevCycle(sdkKey, user, { ...options, deferInitialization: true, ...jsClientOptions, }); let config = null; try { config = await getBucketedConfig(configData.config, configData.lastModified, user, options, userAgent); } catch (e) { console.error('Error fetching DevCycle config', e); } client.synchronizeBootstrapData(config, user, userAgent); return { config, user, userAgent, client }; }); export const validateSDKKey = (sdkKey, type) => { if (!sdkKey) { throw new Error(`Missing ${type} SDK key! Provide a valid SDK key to DevCycleServersideProvider`); } // attempt to make sure server keys don't leak to the client! if ((sdkKey === null || sdkKey === void 0 ? void 0 : sdkKey.length) && !sdkKey.startsWith(`dvc_${type}`) && !sdkKey.startsWith(type)) { throw new Error(`Must use a ${type} SDK key.`); } }; //# sourceMappingURL=initialize.js.map