Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

[FE-3036] feat(studio): runtime env var overrides for enabled features (#45049)

Alaister Young19027e73f8aa
diff --git a/apps/studio/data/misc/enabled-features-override-query.ts b/apps/studio/data/misc/enabled-features-override-query.ts
new file mode 100644
index 00000000000..5c08b9ecbd3
--- /dev/null
+++ b/apps/studio/data/misc/enabled-features-override-query.ts
@@ -0,0 +1,33 @@
+import { useQuery } from '@tanstack/react-query'
+
+import { miscKeys } from './keys'
+import { fetchHandler } from '@/data/fetchers'
+import { BASE_PATH, IS_PLATFORM } from '@/lib/constants'
+import type { ResponseError, UseCustomQueryOptions } from '@/types'
+
+type EnabledFeaturesOverride = { disabled_features: string[] }
+
+export async function getEnabledFeaturesOverride(signal?: AbortSignal) {
+ const res = await fetchHandler(`${BASE_PATH}/api/enabled-features-overrides`, { signal })
+ if (!res.ok) throw new Error(`Failed to fetch enabled features override (${res.status})`)
+ return (await res.json()) as EnabledFeaturesOverride
+}
+
+export type EnabledFeaturesOverrideData = Awaited<ReturnType<typeof getEnabledFeaturesOverride>>
+export type EnabledFeaturesOverrideError = ResponseError
+
+export const useEnabledFeaturesOverrideQuery = <TData = EnabledFeaturesOverrideData>({
+ enabled = true,
+ ...options
+}: UseCustomQueryOptions<EnabledFeaturesOverrideData, EnabledFeaturesOverrideError, TData> = {}) =>
+ useQuery<EnabledFeaturesOverrideData, EnabledFeaturesOverrideError, TData>({
+ queryKey: miscKeys.enabledFeaturesOverride(),
+ queryFn: ({ signal }) => getEnabledFeaturesOverride(signal),
+ enabled: enabled && !IS_PLATFORM,
+ staleTime: Infinity,
+ gcTime: Infinity,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
+ refetchOnReconnect: false,
+ ...options,
+ })
diff --git a/apps/studio/data/misc/keys.ts b/apps/studio/data/misc/keys.ts
index c859f6ad908..02ec349d343 100644
--- a/apps/studio/data/misc/keys.ts
+++ b/apps/studio/data/misc/keys.ts
@@ -4,4 +4,5 @@ export const miscKeys = {
['defaultRegion', [cloudProvider, useRestrictedPool]] as const,
ipAddress: () => ['ip-address'] as const,
clockSkew: () => ['clock-skew'] as const,
+ enabledFeaturesOverride: () => ['enabled-features-override'] as const,
}
diff --git a/apps/studio/hooks/misc/useIsFeatureEnabled.ts b/apps/studio/hooks/misc/useIsFeatureEnabled.ts
index 44449d21758..d50b7a7c4d1 100644
--- a/apps/studio/hooks/misc/useIsFeatureEnabled.ts
+++ b/apps/studio/hooks/misc/useIsFeatureEnabled.ts
@@ -1,5 +1,6 @@
import { isFeatureEnabled, type Feature } from 'common'
+import { useEnabledFeaturesOverrideQuery } from '@/data/misc/enabled-features-override-query'
import { useProfile } from '@/lib/profile'
function useIsFeatureEnabled<T extends Feature[]>(
@@ -8,7 +9,12 @@ function useIsFeatureEnabled<T extends Feature[]>(
function useIsFeatureEnabled(features: Feature): ReturnType<typeof isFeatureEnabled>
function useIsFeatureEnabled<T extends Feature | Feature[]>(features: T) {
const { profile } = useProfile()
- const disabledFeatures = profile?.disabled_features
+ const { data: override } = useEnabledFeaturesOverrideQuery()
+
+ const disabledFeatures = [
+ ...(profile?.disabled_features ?? []),
+ ...((override?.disabled_features ?? []) as Feature[]),
+ ]
// This code branch is to make the type checker happy, it's intentionally
// the same as the isFeatureEnabled function call below.
diff --git a/apps/studio/pages/api/enabled-features-overrides.ts b/apps/studio/pages/api/enabled-features-overrides.ts
new file mode 100644
index 00000000000..8a9f919995f
--- /dev/null
+++ b/apps/studio/pages/api/enabled-features-overrides.ts
@@ -0,0 +1,18 @@
+import { IS_PLATFORM } from 'common'
+import { getEnabledFeaturesOverrideDisabledList } from 'common/enabled-features/overrides'
+import type { NextApiRequest, NextApiResponse } from 'next'
+
+export default function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET')
+ return res.status(405).end()
+ }
+
+ if (IS_PLATFORM) {
+ return res.status(200).json({ disabled_features: [] })
+ }
+
+ return res.status(200).json({
+ disabled_features: getEnabledFeaturesOverrideDisabledList(process.env),
+ })
+}
diff --git a/e2e/studio/features/enabled-features-overrides.spec.ts b/e2e/studio/features/enabled-features-overrides.spec.ts
new file mode 100644
index 00000000000..dea9209b918
--- /dev/null
+++ b/e2e/studio/features/enabled-features-overrides.spec.ts
@@ -0,0 +1,46 @@
+import { expect } from '@playwright/test'
+
+import { env } from '../env.config.js'
+import { test } from '../utils/test.js'
+import { toUrl } from '../utils/to-url.js'
+
+test.describe('Enabled features runtime override', () => {
+ test.skip(
+ env.IS_PLATFORM,
+ 'runtime override is only served on self-hosted; the hook is disabled when IS_PLATFORM'
+ )
+
+ test('GET /api/enabled-features-overrides returns an empty disabled_features list with no overrides set', async ({
+ page,
+ }) => {
+ const res = await page.request.get(toUrl('/api/enabled-features-overrides'))
+
+ expect(res.ok(), 'route should respond 2xx').toBeTruthy()
+
+ const body = await res.json()
+ expect(
+ body,
+ 'route should return { disabled_features: [] } when no ENABLED_FEATURES_* env vars are set'
+ ).toEqual({ disabled_features: [] })
+ })
+
+ test('UI hides the logs templates page when override disables logs:templates', async ({
+ page,
+ ref,
+ }) => {
+ await page.route('**/api/enabled-features-overrides', async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ disabled_features: ['logs:templates'] }),
+ })
+ })
+
+ await page.goto(toUrl(`/project/${ref}/logs/explorer/templates`))
+
+ await expect(
+ page.getByText('Looking for something?', { exact: true }),
+ 'UnknownInterface fallback should render when logs:templates is disabled by the runtime override'
+ ).toBeVisible({ timeout: 15000 })
+ })
+})
diff --git a/packages/common/enabled-features/README.md b/packages/common/enabled-features/README.md
new file mode 100644
index 00000000000..cf3f334786f
--- /dev/null
+++ b/packages/common/enabled-features/README.md
@@ -0,0 +1,71 @@
+# enabled-features
+
+Static feature-flag source used across Studio, docs, and www. The source of truth is `enabled-features.json`; every flag listed there is enabled (`true`) or disabled (`false`) at build time.
+
+## Using a flag
+
+```ts
+import { isFeatureEnabled } from 'common/enabled-features'
+
+if (isFeatureEnabled('logs:templates')) {
+ // ...
+}
+
+const { logsTemplates, logsMetadata } = isFeatureEnabled(['logs:templates', 'logs:metadata'])
+```
+
+Passing an array returns a camelCased object so consumers can destructure.
+
+`isFeatureEnabled(feature, runtimeDisabledFeatures?)` accepts an optional list of features disabled at runtime (e.g. from the authenticated profile) that compose on top of the static defaults.
+
+In Studio, prefer `useIsFeatureEnabled` from `@/hooks/misc/useIsFeatureEnabled` — it layers the authenticated profile's `disabled_features` and the self-hosted runtime override (below) on top of the static JSON.
+
+## Runtime override (Studio self-hosted)
+
+Self-hosted Studio deployments can disable flags at container start time without rebuilding the image. Set one env var per flag under the `ENABLED_FEATURES_` prefix:
+
+```bash
+ENABLED_FEATURES_LOGS_ALL=false
+ENABLED_FEATURES_LOGS_TEMPLATES=false
+ENABLED_FEATURES_BRANDING_LARGE_LOGO=true
+```
+
+Env var values are `true` / `false` (case-insensitive). Any other value is logged and ignored.
+
+### Key → env name mapping
+
+Uppercase the feature key and replace every non-alphanumeric character (`:`, `_`, `-`) with `_`:
+
+| Feature key | Env var name |
+| -------------------------------- | ------------------------------------------------- |
+| `logs:all` | `ENABLED_FEATURES_LOGS_ALL` |
+| `branding:large_logo` | `ENABLED_FEATURES_BRANDING_LARGE_LOGO` |
+| `docs:self-hosting` | `ENABLED_FEATURES_DOCS_SELF_HOSTING` |
+| `logs:show_metadata_ip_template` | `ENABLED_FEATURES_LOGS_SHOW_METADATA_IP_TEMPLATE` |
+
+Mapping is forward-only (known key → expected env name), so snake_case vs colon collisions like `branding:large_logo` / `branding_large:logo` never come up.
+
+Env vars prefixed with `ENABLED_FEATURES_` that don't match a known feature are logged and ignored — a catch for typos.
+
+### Resolution order (Studio runtime)
+
+1. `ENABLED_FEATURES_*` env vars (self-hosted only — route is a no-op when `IS_PLATFORM === true`)
+2. `profile.disabled_features` from `/platform/profile`
+3. `enabled-features.json` static value
+4. Default (enabled)
+
+### Scope & limitations
+
+- **Studio only.** The runtime override is surfaced through a Next.js API route and React Query, which docs and www don't use — their flag resolution stays build-time from `enabled-features.json`.
+- **Hosted is unaffected.** The API route returns an empty list when `IS_PLATFORM === true`; hosted Studio continues to derive disabled features exclusively from the authenticated profile.
+- **Brief flash of unstyled flags.** Before the override fetch resolves, flags default to their JSON value. For features gated as "enabled in JSON, disabled by runtime override", there's a brief window where the UI shows the feature before it's hidden.
+- **`Support.constants.ts` call site is build-time only.** `apps/studio/components/interfaces/Support/Support.constants.ts` calls `isFeatureEnabled('billing:all')` at module load to build `CATEGORY_OPTIONS`, which is then spread into Zod form schemas. That one call site resolves from the static JSON and cannot be runtime-overridden without a larger refactor.
+
+## Disable everything (for tooling)
+
+`ENABLED_FEATURES_OVERRIDE_DISABLE_ALL=true` forces every flag to `false`. Used by the docs embeddings pipeline to produce a filtered index. This is a server-only env (no `NEXT_PUBLIC_` prefix) and short-circuits over everything else.
+
+## Adding a new flag
+
+1. Add the key to `enabled-features.json` with the desired default.
+2. Add the key and a description to `enabled-features.schema.json`, including it in the `required` array.
diff --git a/packages/common/enabled-features/overrides.test.ts b/packages/common/enabled-features/overrides.test.ts
new file mode 100644
index 00000000000..3ff25e14fbd
--- /dev/null
+++ b/packages/common/enabled-features/overrides.test.ts
@@ -0,0 +1,84 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { getEnabledFeaturesOverrideDisabledList } from './overrides'
+
+describe('getEnabledFeaturesOverrideDisabledList', () => {
+ let warnSpy: ReturnType<typeof vi.spyOn>
+
+ beforeEach(() => {
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ })
+
+ afterEach(() => {
+ warnSpy.mockRestore()
+ })
+
+ it('returns empty list when no env vars are set', () => {
+ expect(getEnabledFeaturesOverrideDisabledList({})).toEqual([])
+ })
+
+ it('disables a feature when its env var is "false"', () => {
+ expect(
+ getEnabledFeaturesOverrideDisabledList({ ENABLED_FEATURES_LOGS_TEMPLATES: 'false' })
+ ).toEqual(['logs:templates'])
+ })
+
+ it('does not disable features whose env var is "true"', () => {
+ expect(
+ getEnabledFeaturesOverrideDisabledList({ ENABLED_FEATURES_LOGS_TEMPLATES: 'true' })
+ ).toEqual([])
+ })
+
+ it('accepts booleans case-insensitively and trims whitespace', () => {
+ const result = getEnabledFeaturesOverrideDisabledList({
+ ENABLED_FEATURES_LOGS_TEMPLATES: 'FALSE',
+ ENABLED_FEATURES_LOGS_METADATA: ' False ',
+ })
+ expect(result.sort()).toEqual(['logs:metadata', 'logs:templates'])
+ })
+
+ it('maps snake_case and kebab-case keys to the env name convention', () => {
+ const result = getEnabledFeaturesOverrideDisabledList({
+ ENABLED_FEATURES_BRANDING_LARGE_LOGO: 'false',
+ ENABLED_FEATURES_DOCS_SELF_HOSTING: 'false',
+ })
+ expect(result.sort()).toEqual(['branding:large_logo', 'docs:self-hosting'])
+ })
+
+ it('warns and ignores non-boolean values', () => {
+ expect(
+ getEnabledFeaturesOverrideDisabledList({ ENABLED_FEATURES_LOGS_TEMPLATES: 'maybe' })
+ ).toEqual([])
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('must be "true" or "false"'))
+ })
+
+ it('warns and ignores env vars prefixed but not matching a known feature', () => {
+ expect(
+ getEnabledFeaturesOverrideDisabledList({ ENABLED_FEATURES_NOT_A_FEATURE: 'false' })
+ ).toEqual([])
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('does not match any known feature')
+ )
+ })
+
+ it('does not warn for reserved ENABLED_FEATURES_OVERRIDE_DISABLE_ALL', () => {
+ expect(
+ getEnabledFeaturesOverrideDisabledList({ ENABLED_FEATURES_OVERRIDE_DISABLE_ALL: 'true' })
+ ).toEqual([])
+ expect(warnSpy).not.toHaveBeenCalled()
+ })
+
+ it('ignores env vars outside the prefix without warning', () => {
+ expect(
+ getEnabledFeaturesOverrideDisabledList({ NODE_ENV: 'production', PATH: '/usr/bin' })
+ ).toEqual([])
+ expect(warnSpy).not.toHaveBeenCalled()
+ })
+
+ it('treats an empty string value as unset', () => {
+ expect(getEnabledFeaturesOverrideDisabledList({ ENABLED_FEATURES_LOGS_TEMPLATES: '' })).toEqual(
+ []
+ )
+ expect(warnSpy).not.toHaveBeenCalled()
+ })
+})
diff --git a/packages/common/enabled-features/overrides.ts b/packages/common/enabled-features/overrides.ts
new file mode 100644
index 00000000000..a5d1464a2ab
--- /dev/null
+++ b/packages/common/enabled-features/overrides.ts
@@ -0,0 +1,58 @@
+import enabledFeaturesRaw from './enabled-features.json' with { type: 'json' }
+
+const knownFeatureKeys = Object.keys(enabledFeaturesRaw).filter((key) => key !== '$schema')
+
+const ENV_PREFIX = 'ENABLED_FEATURES_'
+
+// Server-only env var that short-circuits feature resolution; handled by
+// isFeatureEnabled directly, not by this parser.
+const RESERVED_ENV_NAMES = new Set<string>(['ENABLED_FEATURES_OVERRIDE_DISABLE_ALL'])
+
+function featureKeyToEnvName(feature: string): string {
+ return ENV_PREFIX + feature.toUpperCase().replace(/[^A-Z0-9]/g, '_')
+}
+
+function parseBooleanEnv(raw: string): boolean | null {
+ const normalized = raw.trim().toLowerCase()
+ if (normalized === 'true') return true
+ if (normalized === 'false') return false
+ return null
+}
+
+/**
+ * Returns the list of feature keys disabled by ENABLED_FEATURES_* env vars.
+ * Server-only — these are not NEXT_PUBLIC_* and must be read at request time.
+ * Invalid values and prefixed env vars that don't match a known feature are
+ * logged and ignored.
+ */
+export function getEnabledFeaturesOverrideDisabledList(
+ env: Record<string, string | undefined>
+): string[] {
+ const expected = new Map<string, string>()
+ for (const key of knownFeatureKeys) {
+ expected.set(featureKeyToEnvName(key), key)
+ }
+
+ const disabled: string[] = []
+ for (const [envName, featureKey] of expected) {
+ const raw = env[envName]
+ if (raw === undefined || raw === '') continue
+ const parsed = parseBooleanEnv(raw)
+ if (parsed === null) {
+ console.warn(
+ `[enabled-features] ${envName} must be "true" or "false" (got "${raw}"); ignoring.`
+ )
+ continue
+ }
+ if (parsed === false) disabled.push(featureKey)
+ }
+
+ for (const envName of Object.keys(env)) {
+ if (!envName.startsWith(ENV_PREFIX)) continue
+ if (expected.has(envName)) continue
+ if (RESERVED_ENV_NAMES.has(envName)) continue
+ console.warn(`[enabled-features] ${envName} does not match any known feature; ignoring.`)
+ }
+
+ return disabled
+}