import type { ClientFeaturesResponse } from "unleash-client"; import { removeTrailingSlash } from "./utils"; import { version, devDependencies } from "../package.json"; const defaultUrl = "http://localhost:4242/api/client/features"; const defaultToken = "default:development.unleash-insecure-api-token"; const supportedSpecVersion = devDependencies["@unleash/client-specification"]; type FetchOptions = RequestInit & { next?: { revalidate?: number | false; tags?: string[]; }; }; export const getDefaultConfig = (defaultAppName = "nextjs") => { const baseUrl = removeTrailingSlash( process.env.UNLEASH_SERVER_API_URL || process.env.NEXT_PUBLIC_UNLEASH_SERVER_API_URL ); const envToken = process.env.UNLEASH_SERVER_API_TOKEN; const instanceId = process.env.UNLEASH_SERVER_INSTANCE_ID; let token = undefined; if (envToken) { token = envToken; } else if (!instanceId) { token = defaultToken; } return { appName: process.env.UNLEASH_APP_NAME || process.env.NEXT_PUBLIC_UNLEASH_APP_NAME || defaultAppName, url: baseUrl ? `${baseUrl}/client/features` : defaultUrl, ...(token ? { token } : {}), ...(instanceId ? { instanceId } : {}), fetchOptions: {} as FetchOptions, }; }; type CacheEntry = { key: string; etag: string; definitions: ClientFeaturesResponse; }; // A single slot is enough: a given app has one configuration, so the cache // collapses to one entry. We tag it with the request identity so that a // per-call config override never gets served another config's cached body. let definitionsCache: CacheEntry | undefined; // The response depends only on the URL and the token (which scopes // project + environment); other headers are identity metadata, not selectors. const getCacheKey = (url: string, headers: Record) => JSON.stringify({ url, authorization: headers["authorization"] || "", }); /** @internal Test utility to clear the in-memory cache. */ export const __resetDefinitionsCache = () => { definitionsCache = undefined; }; /** * Fetch Server-side feature flags definitions from Unleash API * * If you provide `url` in the config parameter, it should be a full endpoint path: * @example getDefinitions({ url: `http://localhost:4242/api/client/features` }) */ export const getDefinitions = async ( config?: Partial> ) => { const { appName, url, token, instanceId, fetchOptions } = { ...getDefaultConfig(), ...(config || {}), }; if (url === defaultUrl) { console.warn( "Using fallback Unleash API URL (http://localhost:4242/api).", "Provide a URL or set UNLEASH_SERVER_API_URL environment variable." ); } if (token === defaultToken) { console.error( "Using fallback default token. Pass token or set UNLEASH_SERVER_API_TOKEN environment variable." ); } const fetchUrl = new URL(url); const sendAuthorizationToken = !instanceId || token !== defaultToken; const headers: Record = { "content-type": "application/json", "user-agent": appName, "unleash-client-spec": supportedSpecVersion, "unleash-sdk": `unleash-nextjs-sdk:${version}`, "unleash-appname": appName, }; if (sendAuthorizationToken && token) { headers["authorization"] = token; } if (instanceId) { headers["unleash-instanceid"] = instanceId; } if (fetchOptions.headers) { Object.entries(fetchOptions.headers).forEach(([key, value]) => { if (value != null) { headers[key.toLowerCase()] = String(value); } }); } const cacheKey = getCacheKey(fetchUrl.toString(), headers); const cached = definitionsCache?.key === cacheKey ? definitionsCache : undefined; if (!headers["if-none-match"] && cached) { headers["if-none-match"] = cached.etag; } const response = await fetch(fetchUrl.toString(), { ...fetchOptions, headers, }); if (response.status === 304) { // We only send If-None-Match when we hold a cached body, so a 304 with no // matching entry means a caller-supplied If-None-Match (or a misbehaving // server) — we have nothing to return. if (cached) { return cached.definitions; } throw new Error( "Unleash: Received 304 Not Modified but no cached definitions are available." ); } const definitions = (await response.json()) as ClientFeaturesResponse; if (response.ok) { const etag = response.headers?.get?.("etag"); if (etag) { definitionsCache = { key: cacheKey, etag, definitions, }; } else if (definitionsCache?.key === cacheKey) { definitionsCache = undefined; } } return definitions; };