Skip to content

feat(env): validate public env values with zod (#1007) - #1064

Open
divysam wants to merge 2 commits into
Predictify-org:mainfrom
divysam:feat/validate-env-zod
Open

divysam wants to merge 2 commits into
Predictify-org:mainfrom
divysam:feat/validate-env-zod

Conversation

@divysam

@divysam divysam commented Nov 23, 2026

Copy link
Copy Markdown

Summary

Closes #1007.

getEnvVar in lib/env.ts returned '' silently and accepted any string, so a
malformed NEXT_PUBLIC_API_URL or NEXT_PUBLIC_APP_URL (e.g. ftp://…, a host
without a scheme, or a whitespace-only value) flowed straight into
lib/config.ts and from there into metadata, SEO and API clients. It also
silently treated an explicitly empty value (process.env[key] || default) as
unset, while a whitespace-only value passed through unchanged.

This PR validates the public environment with zod (already a dependency),
fails fast in production, and keeps local development unblocked.

What changed

lib/env.ts

  • Zod schema for the public variables exported from the module (env keeps
    its existing shape and defaults, so lib/config.ts needs no change):

    • NEXT_PUBLIC_STELLAR_NETWORK — enum testnet | mainnet, case-insensitive
      (MAINNET is accepted and normalised), default testnet.
    • NEXT_PUBLIC_API_URL / NEXT_PUBLIC_APP_URL — must parse with new URL
      and use http:/https:; trailing slashes are normalised away; default
      http://localhost:3000/api / http://localhost:3000.
    • NEXT_PUBLIC_APP_NAME — non-empty after trimming, default Predictify.
    • NEXT_PUBLIC_ANALYTICS_ID — optional; empty/whitespace disables analytics.
    • NEXT_PUBLIC_USE_MOCKS — true | false, default false.
    • NODE_ENV — non-empty string, default development.
    • Values are trimmed before validation.
  • parseEnv(source: Record<string, string | undefined>) — new pure,
    testable entry point. Missing keys use the documented defaults; invalid input
    throws a single aggregated error listing every problem, e.g.

    Invalid environment variables:
      - NEXT_PUBLIC_API_URL: must be a valid absolute http(s) URL
      - NEXT_PUBLIC_APP_NAME: must not be empty
    
  • resolveEnv(source) — non-throwing helper used to build the exported
    env. Only the offending keys fall back to their defaults; valid values are
    preserved.

  • validateEnv() — applies the same rules to process.env; throws the
    aggregated error in production (and runs automatically on import, as
    before) and warns in development/test while falling back to defaults.
    Invalid values can therefore never leak through the exported env.

Tests — lib/__tests__/env.test.ts (new)

21 cases covering:

  • defaults when variables are unset; valid values pass through unchanged;
  • trailing-slash normalisation and whitespace-padded values;
  • uppercase network (MAINNET) accepted and normalised;
  • rejection of ftp://, scheme-less localhost:3000, empty and
    whitespace-only URLs, empty/whitespace app names and unknown networks;
  • aggregated, readable multi-key errors;
  • optional analytics id ('', ' ' and unset all yield '');
  • resolveEnv fallback keeps valid values and replaces only invalid ones;
  • validateEnv() warns outside production and throws in production;
  • the exported env keeps its key set/defaults and stays compatible with
    lib/config.ts.

Docs

docs/API.md now documents the zod validation, the accepted values and the
production/dev failure behaviour.

Unrelated repairs required for a green CI

main is currently red for reasons unrelated to this issue (recent merges with
no CI run), so pnpm type-check, pnpm test and pnpm build all failed before
this branch even touched them. These are isolated in a second commit
(fix: repair pre-existing typecheck, test and build failures on main):

  • lib/events-store.ts: a truncated export const mockEvents: Event[] = [
    stub (left by the watchlist merge) was a syntax error and broke every import.
    It is now a re-export of the canonical lib/fixtures/events.
  • Navbar.tsx: duplicated lucide-react imports and NAV_ITEMS entries
    without a key (→ t(undefined)); added the missing nav.watchlist /
    nav.creator messages in en/es/fr and fixed the matching MobileBottomTabs
    tab.
  • app/layout.tsx / app/metadata.ts: manifest is a Metadata field, not a
    Viewport field.
  • activity-timeline.tsx: the default mock list was regenerated on every
    render, so its effect looped forever (Maximum update depth exceeded). It is
    now memoised; stale pagination tests were updated to page groups with
    pageSize=1.
  • Fixed broken tests: missing }); in creator.test.ts (nested its), ics
    folding test (built a real MarketCalendarEvent, Buffer.byteLength instead
    of the jsdom-missing TextEncoder), navbar a11y test queried before
    rendering, layout-metadata union-type access.
  • Converted two leftover vitest test files to Jest and completed the i18n mock
    in a11y-routes.test.tsx.
  • formatRelative now uses numeric: "always" so output is stable across ICU
    versions (French dans 2 jours instead of après-demain).

If you would prefer these split into a separate PR, I'm happy to do that.

Verification (Node 24, pnpm 10.18.3)

Check Command Result
Typecheck (CI) pnpm type-check ✅ clean
Tests (CI) pnpm test --ci --maxWorkers=4 ✅ 177 suites / 1941 tests, 5 snapshots
Build (CI) pnpm build ✅ succeeds with default env
New tests pnpm test -- lib/__tests__/env.test.ts ✅ 21 passed
Lint pnpm lint ⚠️ pre-existing errors only (react/no-unescaped-entities, etc.); new/changed files are lint-clean

Edge cases explicitly exercised: ftp://, localhost:3000 without scheme,
uppercase MAINNET, whitespace-padded values, empty/whitespace URLs and app
name, missing variables using defaults, multi-error aggregation, and
production vs. development failure behaviour.

No build output, binaries, .vscode/ or workflow changes are included.

Notes for reviewers

  • Empty is deliberately not treated as "unset": an explicitly empty
    required variable is an error in production and a warning + default elsewhere
    (documented in docs/API.md).
  • NEXT_PUBLIC_USE_MOCKS is now validated as true | false; previously any
    string was accepted and anything other than "true" silently behaved as
    false.
  • env remains a plain object with the same keys/defaults, so lib/config.ts
    and the existing consumers are untouched.

Checklist

divysam and others added 2 commits November 23, 2026 14:03
Replace the silent `getEnvVar` fallback with a zod schema for the public
variables consumed by lib/config.ts. URL values must parse with `new URL` and
use http(s), trailing slashes are normalised, the Stellar network is an enum,
the app name must be non-empty after trimming and the analytics id is optional.

`parseEnv(source)` is pure and throws one aggregated, readable error; the
exported `env` object keeps its previous shape and defaults. In production
`validateEnv()` (run on import) throws on invalid values; outside production
invalid keys fall back to defaults with a warning so local work is not blocked.

Adds lib/__tests__/env.test.ts covering empty/whitespace values, ftp:// and
scheme-less hosts, uppercase networks, whitespace padding, defaults and the
production/dev validation paths. Closes Predictify-org#1007.

Generated with Codebuff 🤖
Co-Authored-By: Codebuff <noreply@codebuff.com>
The repo's CI (typecheck, tests, build) is currently red on main because of
several unrelated merges. Fix them so the env-validation change can land with a
green pipeline:

- lib/events-store.ts: replace the truncated `mockEvents` stub with a re-export
  of the canonical fixtures (watchlist page imports it); fixes syntax errors.
- components/navbar/Navbar.tsx: merge duplicated lucide imports and give every
  NAV_ITEMS entry a translation key (Watchlist/Creator).
- components/navbar/MobileBottomTabs.tsx + i18n catalogs: use `labelKey` for the
  Watchlist tab and add the missing nav.watchlist/nav.creator messages.
- app/layout.tsx, app/metadata.ts: `manifest` belongs to Metadata, not Viewport.
- components/activity-timeline: memoise the generated activity list so the
  effect cannot trigger an infinite setState loop; fix stale pagination tests.
- creator/ics/navbar/layout-metadata tests: close a missing `it` block, fold
  against a real calendar event with Buffer.byteLength, render before querying,
  and query union metadata types safely.
- PWA/install-prompt tests: convert leftover vitest imports/mocks to Jest.
- a11y-routes mock: keep the real i18n formatters and fall back to English.
- i18n formatRelative: use numeric "always" for stable output across ICU.

Generated with Codebuff 🤖
Co-Authored-By: Codebuff <noreply@codebuff.com>
@vercel

vercel Bot commented Nov 23, 2026

Copy link
Copy Markdown

@divysam is attempting to deploy a commit to the Jagadeesh B's projects Team on Vercel.

A member of the Team first needs to authorize it.

@drips-wave

drips-wave Bot commented Nov 23, 2026

Copy link
Copy Markdown

@divysam Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Validate public env values in lib/env.ts with zod

1 participant