Revision 1 of this report, published 2026-11-22. Read the latest version · All revisions
metro · investigation

Bundle environments in Metro

How Metro's config should vary resolution by bundle environment for React Server Components, how that composes with platform and with today's resolver options, and what to call it: three independent analyses, reconciled and checked against Metro, Expo and React Native source.

Metro step 1 38953b5 on main 136bb79Expo fc9e0ccReact Native d6ea9fcVite 3567471Investigated 2026-11-22

Summary

VerdictReplace the draftLand a resolver-scoped map of environments as step 2, not the additive unstable_conditionsByEnvironment. All three analyses prefer it.
Existing optionsConditions addAn environment's entry adds conditions to the top level, and the client gets its own entry. Ordered lists such as main fields replace. Two of three analyses.
NameKeep environmentReact, Vite, Parcel and Expo use the word for this concept. target means language level or build output in most neighbouring tools. All three.
BreakingOne default flipApart from eventually dropping unstable_, only moving Metro's default browser condition onto the client entry breaks anyone. It is flagged first and flipped in a breaking release.

Metro's support for React Server Components starts with two steps. Step 1 adds an environment bundle option, unset for the client, that reaches transformers, resolvers, cache keys and the graph ID. Step 2 is the first config that acts on it. This report is about the shape of step 2 and what surrounds it.

Platform and environment are different axes, and Metro should keep both. Platform is what a bundle renders for: it picks .ios.js files, inlines Platform.OS and selects asset variants. Environment is what runs the code, and on which side of the server/client boundary: it picks runtime conditions such as node, React's react-server build, polyfills and the prelude. They looked like one axis only because every bundle so far has been a client, whose runtime follows from its platform. That is why Metro files the browser condition under web.

Export conditions come from both axes. Platform conditions, which carry per-platform UI such as idiomatic iOS and Android navigation, have to reach server bundles, because a server graph's resolution decides which client module the device loads. Client-runtime conditions (browser, react-native) have to stay out of them. The drafted resolver.unstable_conditionsByEnvironment is the step closest to Metro today and breaks nothing, but it can only add, so a web SSR bundle still resolves ws to its browser stub, which throws. The recommended step 2 is a resolver.unstable_environments map whose entries add conditions, with a client entry for client-only facts, and replace ordered lists such as main fields. Metro computes it in ModuleResolver, so metro-resolver and ResolutionContext don't change.

The three analyses agreed on the two axes, on a resolver-scoped map rather than a top-level section, on the need for a new merge rule, on the name and on the hook arguments. They split two to one on whether entries add or override, whether client can be named, key prefixes and the conditions rename. The agreement section gives each resolution.

Tradeoffs of the recommended design

Breaks some configs
Moving Metro's default browser condition onto the client entry changes configs that had dropped itA config whose top-level unstable_conditionsByPlatform has no web: ['browser'] gets browser back for web client bundles. That includes configs that dropped it by accident: merging {macos: [...]} replaces Metro's whole default map today. It lands behind a flag and flips in a breaking release. The opt-out is client: {unstable_conditionsByPlatform: {}}, because an empty client: {} keeps the default's fields under a merge by environment and then by field.
Two rules
Conditions add, and ordered lists replaceThe docs have to say which rule each key follows. Analysis A's single rule (a value replaces, a function computes) is simpler to state, but its value form silently drops conditions that a user adds at the top level, as the resolver results below show.
Stays in resolvers
Per-platform main fields inside an environment can't be expressedExpo's react-server and SSR main fields differ between web and native. Those, its .mjs ordering and its preferNativePlatform override stay in its resolveRequest. Accepting a function value later is a non-breaking widening.
Edge case
Custom resolvers that rebuild conditions from config bypass environment entriesExpo's tvOS and macOS fallback rebuilds the condition list from static config and overwrites the context's (withMetroMultiPlatform.ts). It has to read the effective values from the context instead. Read from the code, it already overrides Expo's own server conditions in any server bundle built for those platforms, because it runs after Expo's server override. That is inferred, not reproduced.
Verbose
Keys carry two prefixes until stabilisationresolver.unstable_environments.client.unstable_conditionsByPlatform is long. It keeps one naming rule, and one rename when the family stabilises.

Platform and environment are different axes

They answer different questions and enter Metro at different layers: platform from the crawl upwards, environment from the graph downwards. Folding one into the other, as in platform=ios-server, breaks .ios.js lookup, Haste and Platform.OS inlining.

PlatformEnvironment
Question it answersWhat does this output render for?What runs this code, and on which side of the server/client boundary?
Valuesios, android, web, out-of-tree platformsUnset (the client), react-server, an SSR environment (Expo calls it node)
Declaredresolver.platforms, server-wide, feeding Haste (createFileMap.js)Free-form, per request
Selects.ios.js and .native.js files (resolve.js), Platform.OS inlining, asset variants, platform identity conditionsRuntime conditions (node, workerd), role conditions (react-server), polyfills, the prelude, proxy transforms
Reaches, after step 1Transform options, graph ID, its own resolution cache level, getPolyfills({platform}), getTransformOptionsTransform key, graph ID, resolution cache key, caller.environment, context.environment. No config hook receives it yet.

As identifiers they are orthogonal, and the cross product is in use. Expo renders react-server per client platform: it loads the renderer with {environment: 'react-server', platform} and caches it by platform (createServerComponentsMiddleware.ts). A react-server bundle for iOS runs in Node but still needs .ios.js files and Platform.OS === 'ios'. As semantics they are not orthogonal. The client's runtime is a function of platform: Hermes with React Native's globals on iOS and Android, a browser on web. A server's runtime is a function of the environment.

The working definition, "platform is where the app is consumed, environment is where the code runs", needs two corrections, and all three analyses make both. Platform is what the output renders for, not where it is consumed: Expo bundles DOM components with platform: 'web' (DomComponentsMiddleware.ts), although they run inside an iOS or Android app. Environment is a role as well as a place: Expo's SSR and react-server bundles run in the same Node process and differ in which React build they load. React's docs say Server Components render "in an environment separate from your client app or SSR server" (react.dev). React's server module RFC says the react-server condition "applies only React Server Component environments", and that client environments "are the default" (RFC 227).

Prior art has one axis, and it is Metro's environment

ToolOptionValuesWhat it sets
webpacktargetweb, node, webworker, Electron and others, and also es5, es2020 and browserslistThe browser, node or worker condition, and main fields browser, module, main for web or module, main otherwise (docs)
esbuildplatformbrowser, node, neutralThe browser or node condition, and main fields (docs)
Buntargetbrowser, bun, node"The intended execution environment for the bundle", preferring the browser or node condition (docs)
ParcelA target's contextnode, browser, web-worker and others, plus react-server and react-client in its RSC recipeThe environment of the target's modules (RSC recipe)
ViteNamed environments, each with a consumerclient, ssr, and rsc in its RSC plugin (README). consumer is client or server.Server environments default to conditions and main fields without browser (constants.ts)

esbuild calls this axis platform, which is Metro's environment. None of these tools has a counterpart to Metro's platform, because the web has one UI host.

A React Native bundler designed today keeps both axes, with a bundle's identity being its entry, platform, environment and mode, and composes conditions as a union of independent facts. Platform extensions stay a platform-only mechanism: React's RFC dropped environment-specific file names ("No more file extension conventions", RFC 227). Two further points come from one analysis each. Analysis A adds Turbopack-style transitions, where a "use client" edge re-resolves its specifier in the client environment. Analysis C adds platform families such as tvos, then ios, then native. Metro hard-codes preferNativePlatform: true (createModuleResolver.js), so a plain Metro web bundle prefers .native.js over .js. That is a platform-axis gap, outside this report.

Conditions belong to both axes

KindExamplesBelongs to
Platform identityios, android, custom UI conditionsThe platform, in every environment
Client runtimebrowser on web, react-native on iOS and AndroidThe client environment, per platform
Server runtimenode, workerd, edge-lightServer environments
React rolereact-serverThe react-server environment
Projectdevelopment, a monorepo source conditionEvery bundle (the top level)
Module formatimport, require, defaultMetro, per import edge

WinterTC's draft runtime keys define react-native as "supported React Native JS runtimes on native platforms (excludes react-native-web)" and list react-server as "Used by React Server Components". They leave browsers out entirely (runtime keys). Node defines browser as "any web browser environment". Packages also use react-native to mean the native UI, so it is the one condition with two owners.

Platform conditions have to reach server bundles because the server's resolution picks the client's file. Expo's client proxy plugin keys each reference by the path of the file the server graph resolved (client-module-proxy-plugin.ts), and builds the client chunk URL from the same path (createServerComponentsMiddleware.ts). If a react-server bundle for iOS drops a package's ios condition, the iOS client is sent the default build. For an exported subpath, a condition is the only per-platform switch a package has, because Metro looks up an exports target as an exact path, with no platform extensions (PackageExportsResolve.js).

Config shapes

All three analyses reject a top-level environments section and recommend a map of environments under resolver, keyed by environment name, whose entries reuse resolver option names. In every recommended variant, Metro computes each environment's effective options in ModuleResolver, which already builds a fresh context for every resolution (ModuleResolution.js), and passes them in the context fields that custom resolvers already read. metro-resolver doesn't change. ModuleResolver's options type may have Meta-internal consumers, so its one new option is optional.

Every shape needs a merge rule. mergeConfig spreads resolver one level deep and merges only schemeResolvers by key (loadConfig.js). Running it confirms that a user config with {worker: [...]} replaces a framework's map of react-server and node entries, whether the map is unstable_conditionsByEnvironment, resolver.environments or a top-level environments. The hazard exists today: merging unstable_conditionsByPlatform: {macos: [...]} drops Metro's default web: ['browser']. The new map needs a merge by environment and then by field, like watcher.healthCheck.

ShapeKeeps browser out of web SSRKeeps platform conditions in serversPer-environment main fieldsCan name the clientNew ResolutionContext fieldAnalyses
(a) unstable_conditionsByEnvironment, additive (the draft)NoYesNoNoYesClosest to today. None recommends it as step 2.
(b) The same map, replacingYesNoNoNoYesRejected by all
(c) One …ByEnvironment map per optionAs (a) or (b)As (a) or (b)YesNoSeveralRejected by all
(d) Top-level environments with resolver, transformer, serializerDepends on semanticsDependsYesYesDependsRejected by all
(e) resolver.unstable_environments: a value replaces, a function computesYesOnly in the function formYes, per platform through a functionNo, it's an errorNoRecommended by A
(e′) resolver.unstable_environments: conditions add, lists replace, client entryYes, once browser is on clientYesYes, one list per environmentYesNoRecommended by B and C
(f) A hook such as getEnvironmentOptions({platform, environment})YesYesYesYesNoRejected by all: it can only be wrapped, not merged, and resolveRequest with context.environment is already that escape hatch

A top-level section is the right shape only for a bundler built around environments from the start. In Metro, most of the config is process-scoped:

  • The file map. It crawls one extension set, sourceExts, assetExts and additionalExts together (createFileMap.js), so an environment can reorder or narrow sourceExts but never add to it.
  • The transformer config. It is hashed into one base cache key (Transformer.js). Per-environment transformer settings need a base hash and a worker config per environment, and gain nothing: the environment already reaches transformers as options.environment and caller.environment, and Expo varies its transforms that way.
  • The serializer. Its per-bundle variation points, getPolyfills and getModulesRunBeforeMainModule, are already functions. They need the environment as an argument, not a second copy of the section. Module IDs must also agree across environments for client references, so a per-environment createModuleIdFactory is a hazard (Analysis B).

The recommended shape, with a framework's config as the example:

resolver: {
  // Facts true of every bundle for a platform, in every environment.
  unstable_conditionsByPlatform: {ios: ['ios'], android: ['android']},
  unstable_environments: {
    // Bundles with no environment. Client-runtime facts live here.
    client: {
      unstable_conditionsByPlatform: {web: ['browser'], ios: ['react-native'], android: ['react-native']},
    },
    ssr: {unstable_conditionNames: ['node'], resolverMainFields: ['main', 'module']},
    'react-server': {unstable_conditionNames: ['react-server', 'node'], resolverMainFields: ['module', 'main']},
  },
},

A bundle for environment e (the client when unset) on platform p asserts default, import or require, the top-level unstable_conditionNames and unstable_conditionsByPlatform[p], and e's unstable_conditionNames and unstable_conditionsByPlatform[p]. Its main fields are e's resolverMainFields if set, and the top level's otherwise. An environment with no entry gets the top level only. Config layers still replace field values, so a user can change one field of a framework's environment without restating the rest.

How existing options interact with environment entries

Conditions should add to the top level, ordered lists should replace it, and per-bundle functions should receive the environment as an argument, as they already receive the platform. Analyses B and C hold this position. Analysis A proposes one rule for every field: a value replaces, and a function (inherited, {platform}) => value computes. Both reach correct results in every case below. They differ in what a framework has to write, and in what happens to conditions a user adds.

Analysis AAnalysis BAnalysis C
Conditions in an entryReplace, or computed by a functionAddAdd
Main fields in an entryReplace, or a per-platform functionReplaceReplace
sourceExts in an entryYes, within the crawled setLater, within the crawled setNo, leave it to resolveRequest
A client entryA config errorApplies to unsetApplies to unset
How browser leaves server bundlesEach server entry removes itIt moves to the client entryIt moves to the client entry

Resolver results under each design

BundlePackageDraft (additive)Replace, or override valueOverride functionAdd, with client entry
Client, iOSmultinative.jsnative.jsnative.jsnative.js
Client, iOSnav-libios.jsios.jsios.jsios.js
SSR, webwsbrowser.jsindex.jsindex.jsindex.js
react-server, webmultibrowser.jsnode.jsnode.jsnode.js
react-server, iOSnav-libios.jsdefault.jsios.jsios.js
react-server, iOSmultinative.jsnode.jsnode.jsnode.js

Each cell is metro-resolver's result for the package's root export. The framework config asserts react-native on iOS and Android and browser on web, and a user adds ios and android. Server environments assert node, plus react-server where named. ws uses ws 8.23.0's exports in its published tarball's key order (browser, import, require), and its browser.js throws "ws does not work in the browser". nav-lib maps ios, android and default; multi maps react-native, browser, node and default. The last row isn't marked: whether a native server bundle should load React Native builds is the framework's call. On React Native's default config, which asserts react-native everywhere, the draft resolves multi to native.js even for a web react-server bundle.

Adding holds for conditions because they are a set. matchSubpathFromExportsLike builds a Set (L42), and reduceConditionalExport walks the package's keys (L81), so the order of conditions in config never matters. The only question is which facts are present, and placement answers it. If the top level holds only facts that are true of every bundle, nothing ever has to be removed. For the same reason there is no precedence to define between platform and environment conditions.

Overriding works, but composes badly. A framework that writes the obvious value, unstable_conditionsByPlatform: {}, to drop browser from react-server also drops every platform condition a user adds at the top level: that is the nav-lib row. Analysis A's field-for-field translation of Expo's server branch uses the value form. The function form avoids the problem, but then every framework has to classify each inherited condition as runtime or identity, and react-native has no single answer.

Vite met the same problem from the other side. Vite 6 stopped server environments inheriting resolve.conditions, so that defaults could be removed (vitejs/vite#18395, "allow removing conditions"). Only the client now inherits the top-level conditions and main fields (config.ts, L1732). The cost was that a user's top-level condition vanished from Vitest's SSR environment (vitest-dev/vitest#6992). Adding, with a client entry, gets Vite's placement of browser on the client while keeping inheritance, which all three analyses want.

Main fields need per-environment values for correctness, not only conditions. Metro's default resolverMainFields is ['browser', 'main'] (defaults), and React Native's is ['react-native', 'browser', 'main'] (index.flow.js). With browser in the list, a server bundle applies a package's browser field replacements. Since Metro 0.88.0 it applies them to the files that exports resolve to as well (unstable_applyBrowserSpecAfterExports, on by default, resolve.js).

SSR bundle on web, conditions nodeMain fields browser, mainMain fields main
exports: {node, default} with browser: {"./node.js": "./browser.js"}browser.jsnode.js
fs from a package with browser: {fs: false}The empty moduleNot replaced

Which options vary per environment

OptionPer environment?Mechanism
unstable_conditionNames, unstable_conditionsByPlatformYes (all three)Entry fields that add to the top level
resolverMainFieldsYes (all three)An entry field that replaces. Per-platform values are open.
sourceExtsOpen: A yes, B later, C noExpo only moves .mjs after .js for servers (L833). If added, it has to stay within the crawled set.
platforms, platform extensions, assetExtsNo (all three)Crawl-time and server-wide. Expo varies asset output by environment through transform options instead.
preferNativePlatformNo (all three)A platform fact, hard-coded today. Expo sets platform !== 'web' for every environment (L829).
resolveRequest, schemeResolversNoLogic reads context.environment, from step 1
getTransformOptionsYes (all three)Add environment to its options (transformHelpers.js)
getPolyfillsYes (all three)Add environment to its context (getPrependedScripts.js). Expo empties its streams polyfill for servers in its transformer today (transform-worker.ts), because the hook can't tell.
getModulesRunBeforeMainModuleYes (all three)An optional second argument, {platform, environment}. It receives only the entry path today (Server.js), so it can't tell a server bundle from a client one.
Static transformer configNo (all three)Hashed once; transformers branch on options.environment
Custom serializersNo new configThey read graph.transformOptions.environment
createModuleIdFactoryContext, not configThe planned module ID context step
Reporter bundleDetailsYes (A, B)Add environment. Expo labels server bundles from custom options today.

The client. The top-level options are the client's base, and the client entry adds facts that are true only of the client. Step 1 should also normalise environment=client to unset, as it already does for '' and null (splitBundleOptions.js), so that both spellings share one graph and its caches. Expo already maps client to undefined (metroOptions.ts). All three analyses ask for this, and it is free only until step 1 ships.

Lookups. They must use own properties. With the draft, environment=constructor or environment=toString throws a TypeError during resolution, and platform=constructor does the same through unstable_conditionsByPlatform on main. Metro passes both values from the bundle URL without validation (platform, environment).

Cache keys. None of the resolver shapes touches a persistent key. Resolver config isn't in the transform key, apart from unstable_allowVirtualModules (L157). The in-memory resolution cache is partitioned by resolver options, which include the environment after step 1 (DependencyGraph.js). Config is fixed for a server's lifetime. Prepended polyfills are built per graph, so the hook arguments are cache-safe too. Only per-environment transformer config, shape (d), needs a base hash per environment.

The name

Keep environment. All three analyses reject every alternative. React uses the word for exactly this split, as quoted above. Vite's Environment API names its environments client and ssr, and its RSC plugin adds rsc. Parcel says "Each module in Parcel has an associated environment" (How Parcel bundles React Server Components). Expo already sends environment with the values node, react-server and client (MetroEnvironment), in two custom-option bags (L407). The cost is collisions with process.env, NODE_ENV, and Babel's envName and api.env(), which all mean development versus production. Metro's docs should never call a mode an environment.

CandidateWhy not
targetBabel's targets ("the environments you support/target") and TypeScript's target mean language level. webpack's target mixes runtimes (web, node) with ECMAScript versions (es5) and browserslist queries (docs). Parcel's targets are output configurations: "Parcel can compile your source code in multiple different ways simultaneously. These are called targets." metro-resolver already returns an exports target from matchSubpathFromExportsLike. Bun's target is the runtime, but it names the runtime without the role. In React Native, "target" also reads as a build target or a target platform, the confusion this option has to avoid (a judgement, not measured).
runtimeSSR and react-server share a runtime, so it mislabels the distinction that matters. It also collides with metro-runtime and Babel's runtime.
consumerIn Vite it is a binary attribute of an environment, client or server (config.ts), not the dimension itself.
layerwebpack's per-module tag within one compilation. It presumes per-module environment switching, which Metro's RSC design leaves open.
contextResolutionContext and require.context already use it.

Analysis C notes that "target" fits the pair of platform and environment, the full description of what a bundle is for. Metro has no API that needs a name for the pair today, so that is a docs-vocabulary option, not a config key.

Values. They stay free-form strings, with client reserved. Analyses A and C suggest naming environments for roles (react-server, ssr) and expressing runtimes as conditions. Expo's react-server asserts both node and workerd (L868), so one role can deploy to several runtimes. A name like node stops fitting when SSR runs on workerd. Analysis B treats Expo's names as the conventions to document. Three things are not environments: DOM components (the web client with an entry option), development versus production (the mode), and worklets (per-module, inside the client graph).

conditionNames or conditions. Metro added unstable_conditionNames and unstable_conditionsByPlatform together in January 2023, as config ahead of package exports support (5c6897e), with no rationale recorded. Of the tools checked, only webpack says conditionNames. Node (--conditions), Vite and esbuild say conditions, TypeScript says customConditions, and Metro's own sibling says conditionsByPlatform. Inside environment entries, mirror today's names. Analyses A and C rename the family to conditions when it drops unstable_, since every config edits those keys at that point anyway. Analysis B keeps conditionNames to avoid churn with no change in behaviour. Custom resolvers that read or write context.unstable_conditionNames, as Expo's do, change in that release either way.

Prefixes. environment itself is unprefixed, as settled. Analyses A and C prefix the container, resolver.unstable_environments, because inheritance and the add-or-replace rules are new. Analysis B leaves it unprefixed, to commit to the container and its merge rule. Inside entries, A and B mirror the top-level names exactly, unstable_ included, so that one rule holds ("the same name as the option it extends") and one release renames both levels. C drops the inner prefixes, following watcher.unstable_autoSaveCache.{enabled, debounceMs}. That precedent's fields don't mirror top-level options, so it doesn't settle the question. The recommendation is the majority on each: a prefixed container with mirrored inner names.

The two horizons

Both horizons ship step 1, reserve client and pass environment to the per-bundle hooks. They differ in step 2, and only the ideal horizon has anything to flip later.

Closest to Metro todayIdeal, achievable in months
Step 1As it is, plus environment=client normalised to unsetThe same
Step 2The drafted resolver.unstable_conditionsByEnvironment, additive, with own-property lookupsresolver.unstable_environments: conditions add, resolverMainFields replaces, a client entry, merged by environment then field, own-property lookups and allowlisted keys
Hooksenvironment for getTransformOptions and getPolyfills, and an optional second argument for getModulesRunBeforeMainModuleThe same, plus bundleDetails, Metro.buildGraph and runBuild, and metro build --environment
Keeps browser out of web SSROnly through resolveRequestThrough config
Expo's server overrideStays whole (L832–872)Conditions move to config. Per-platform main fields, .mjs order and preferNativePlatform stay.
Later breaking releaseNothing to flip, but the draft becomes an overlapping option to retireMetro's default browser moves to the client entry. The family drops unstable_, and possibly becomes conditions.
Size22 lines of source, excluding tests and docsAbout the draft's size for conditions and main fields, plus a merge case and validation. This is Analysis C's estimate, not prototyped.

What breaks, and for whom

ChangeMetro usersReact Native community CLIExpo (pins Metro)
Step 1, with client normalisedNothing. With the environment unset, transform keys, resolution keys and graph IDs are byte-identical, and step 1's tests pin the transform key and graph ID.Nothing. Babel plugins see caller.environment only once @react-native/metro-babel-transformer forwards it, because it lists its caller keys (index.js).Nothing on the bump: Expo sends resolver.environment and transform.environment, not environment. Adopting environment costs one transform cache miss per file.
Hook argumentsNothing at runtime. A Flow config that annotates getTransformOptions' options as an exact {dev, platform} must widen the annotation (GetTransformOptionsOpts is exact). TypeScript and untyped configs are unaffected.NothingNothing. Expo calls getModulesRunBeforeMainModule itself with one argument (Chunk.ts), so the second argument has to be optional. Expo can drop its streams-polyfill transform workaround.
Step 2, closestNothing: the map defaults to {}Nothing, but its global react-native condition reaches server bundles and config can't remove itNothing. It can move react-server into config, and keeps its override.
Step 2, idealNothing: absent by defaultNothing: it defines no environmentsNothing. It can partition its conditions into the map and delete the conditions half of its override. Its tvOS and macOS fallback has to read conditions from the context.
Flip: browser moves to clientConfigs whose top-level unstable_conditionsByPlatform lacks web: ['browser'] get it back for web client bundlesNothing: its config sets no platform map (index.flow.js). Moving react-native from unstable_conditionNames to client is React Native's own call, and changes only configs that replace unstable_conditionNames.Nothing. Its own web: ['browser'] (ExpoMetroConfig.ts) becomes a harmless duplicate.
Unprefix, and the conditions renameEvery config that sets the condition options@react-native/metro-config renames unstable_conditionNames in the React Native release that takes the Metro bumpRenames in @expo/metro-config, and in the context fields its resolvers write, on the bump that carries it

Staying non-breaking compromises the defaults, not the shape. Three defaults put runtime facts in the shared base: Metro's browser in unstable_conditionsByPlatform.web and in resolverMainFields, and React Native's universal react-native condition. A framework can partition its own defaults on day one, because the map is the opt-in. Main fields can't be fixed by a client default, since a client value replaces and so shadows a user's top-level value, so every server environment sets its own (Analysis C).

Where the analyses agreed and disagreed

The analyses agree on the model and most of the design. Where they split, it is usually two to one. Each split is resolved below, either on the evidence or as an open decision with a recommendation.

TopicAnalysis AAnalysis BAnalysis CResolution
Agreed by all three
Platform and environmentSeparate axes; keep both. Platform is what output renders for; environment is the runtime and React role. Prior art's single axis is Metro's environment.Holds
ConditionsCome from both axes. Platform identity conditions must reach server bundles. No precedence: a set, matched in the package's key order.Holds; resolver results above
Shape familyA resolver-scoped, environment-major map computed in ModuleResolver. Reject (b), (c), (d) and (f).Holds
MergingmergeConfig replaces maps wholesale; the new map needs a by-environment mergeHolds; ran mergeConfig
InheritanceEnvironments inherit the top levelHolds; Vite's non-inheritance broke vitest-dev/vitest#6992
Main fieldsVary per environment and replaceHolds; browser field replacements reach server bundles
client in URLsNormalise environment=client to unset in step 1, before it shipsHolds
Hook argumentsenvironment for getTransformOptions, getPolyfills, getModulesRunBeforeMainModule. A and C put it in the near term, B in the ideal horizon.Independent and additive; ship with either
LookupsOwn-property only, in the new map and in unstable_conditionsByPlatformHolds; reproduced the TypeError
NameKeep environment; reject target, runtime, consumer, layer, contextHolds
Split
Semantics of an entryA value replaces; a function computesConditions add; lists replaceConditions add; lists replaceB and C hold for conditions: they compose with user additions, and A's value form doesn't
A client entryAn errorApplies to unsetApplies to unsetB and C; it follows from adding
The draft as step 2Ship it only in the closest horizon; recommends (e) insteadDon't ship it as it isOnly if a react-server condition is needed before the shape is agreedAll prefer a structured map. The draft is a stopgap only.
Default browser flipNot needed under overrideFlag, then flipFlip; the map is the opt-inFollows from adding. Recommended, flagged first.
Per-platform main fieldsFunction formNot addressed; claims Expo can drop its whole overrideStays in resolvers; a platform-axis gapOpen. Recommend C, and widen to functions later if needed.
sourceExtsYesLaterNoOpen. Recommend deferring; Expo's only use is a reorder.
Container keyunstable_environmentsenvironmentsunstable_environmentsRecommend the prefix (A and C)
Keys inside entriesMirror, with unstable_Mirror, with unstable_UnprefixedRecommend mirroring (A and B)
conditions renameAt the unprefix releaseNeverAt the unprefix releaseOpen. Recommend renaming then (A and C).
Environment valuesName for rolesDocument Expo's namesName for rolesDocs use role names; values stay free-form
Raised by one or two
Config-reading resolversRaisedNot raisedRaised, with the tvOS and macOS caseAccepted; inferred from code, not reproduced
Client-reference mismatchRe-resolve each client reference in the client environment when building reference sets, and warn on a mismatchNot raisedNotes the server's resolution decidesWorth adding to the reference-sets step
Unknown environment namesNot raisedTop level only; maybe warnUnbounded values from URLs; defer declaring themOpen; defer
react-native on native serversTwo ownersExpo drops the condition but keeps the main fieldThe framework decides by placementThe framework's call; the shape supports either

Claims corrected or dropped

  • Analysis B: "Expo can delete its entire server override" with per-environment main fields and sourceExts. Corrected. Expo's react-server and SSR main fields differ between web and native (L845–865), which one list per environment can't express, and its preferNativePlatform override is per platform.
  • Analysis B: the flip breaks only configs that remove browser on purpose. Corrected. It also changes configs that replaced the platform map for another reason.
  • Analysis C: the opt-out from the flip is client: {}. Corrected. Under a merge by environment then field, which all three recommend, an empty entry keeps the default's fields. The opt-out is client: {unstable_conditionsByPlatform: {}}.
  • Analysis A: vitejs/vite#18648 stopped SSR inheriting resolve.conditions. Corrected to vitejs/vite#18395. #18648 only exported the default lists.
  • Analysis A: making GetTransformOptionsOpts inexact avoids the Flow break. Dropped. Flow 0.341.0 rejects a hand-written exact {dev, platform} annotation against both an exact and an inexact widened type.
  • Analysis C: Vite's server conditions are "the client defaults minus browser". Corrected. The server default is module, node, development|production, and the client's is module, browser, development|production. The main-field claim holds.

Claims that Analysis B labelled as from memory (Vite's per-environment conditions, WinterTC's react-native key) were checked and hold. Analysis C's observation that React's Flight server package resolves a web react-server bundle that asserts browser and edge-light to its edge build only because its exports lists edge-light first holds against react-server-dom-webpack 19.3.1's published tarball.

Decisions left open

  • Function values in entries. They let main fields vary by platform inside an environment, at the cost of opaque config and purity rules. Recommendation: none at first. Accepting functions later is a widening that breaks no config.
  • Per-environment sourceExts. The only use found is Expo moving .mjs after .js for servers. Recommendation: defer. If added, replace within the crawled set, validated at load.
  • Key names. Recommendation: resolver.unstable_environments, with entry keys that mirror the top-level names exactly.
  • The conditions rename. Recommendation: rename when the family drops unstable_, accepting the old names with a warning for one release.
  • Unknown environment names. A warning when the map is non-empty and the name has no entry, or declared environments. Recommendation: defer until Metro acts on an environment beyond config.

Recommendation

  • Normalise environment=client to unset in step 1, before it ships.
  • Land resolver.unstable_environments as step 2 instead of the drafted unstable_conditionsByEnvironment: conditions add, resolverMainFields replaces, a client entry, a merge by environment then field, own-property lookups and allowlisted keys. Fix the same lookup in unstable_conditionsByPlatform.
  • Pass environment to getTransformOptions and getPolyfills, and as an optional second argument to getModulesRunBeforeMainModule. Add it to bundleDetails, Metro.buildGraph and the CLI.
  • Document the partition from day one: the top level holds facts for every bundle, and client holds client-runtime facts. Then flag, and flip in a breaking release, Metro's default browser onto the client entry.
  • Keep the name environment. Decide the conditions rename when the family drops unstable_.
  • When building reference sets, re-resolve each client reference in the client environment and warn on a mismatch.

Method

Three analyses were produced independently by AI agents from the same brief: the question, the context, and settled constraints such as the unprefixed environment option and the client as the absent environment. Each read Metro's source, Expo's source and prior art. A fourth agent reconciled them. It checked every disputed claim, and every load-bearing claim made by only one analysis, against the code at the commits in the header, and dropped or corrected those that didn't hold. Judgements and inferences are labelled where they appear.

Metro code was read at step 1 (38953b5, on main 136bb79) and at a draft of step 2, whose resolver change is three lines in matchSubpathFromExportsLike that append the conditions for context.environment. mergeConfig and metro-resolver were run from the draft's checkout, where both behave as at step 1 when the new option is unset. The resolver script builds in-memory packages with metro-resolver's test helper, computes each design's effective options, and resolves through Resolver.resolve. Package exports key orders come from the published tarballs, because the npm registry's metadata lists ws's conditions in a different order. The Flow result comes from Flow 0.341.0 on a standalone file. Expo was read at fc9e0cc, React Native at d6ea9fc, Vite at 3567471 and React's RFCs at c15bc9d. Documentation pages were read on 2026-11-22.

Not verified: Expo's tvOS and macOS server-condition loss (read from the order of its resolvers, not run); how Next.js and Parcel handle a client reference whose server and client resolutions differ; and the size estimate for the recommended step 2, which has not been prototyped.

Resolver matrix script
// Resolves mock packages with metro-resolver under the effective options each
// candidate design gives a bundle. Usage: node matrix.js <metro checkout>
'use strict';
const path = require('node:path');
const METRO = process.argv[2];
require(path.join(METRO, 'packages/metro-babel-register')).unstable_registerForMetroMonorepo();
const Resolver = require(path.join(METRO, 'packages/metro-resolver/src/index.js'));
const {createResolutionContext} = require(path.join(METRO, 'packages/metro-resolver/src/__tests__/utils.js'));

const nm = '/root/node_modules';
const pkg = (name, json, files) => ({
  [`${nm}/${name}/package.json`]: JSON.stringify({name, ...json}),
  ...Object.fromEntries(files.map(f => [`${nm}/${name}/${f}`, ''])),
});
const base = {
  ...createResolutionContext({
    '/root/app/index.js': '',
    // ws@8.23.0's "exports", in the key order of its published tarball.
    ...pkg('ws', {main: 'index.js', browser: 'browser.js', exports: {'.': {browser: './browser.js', import: './wrapper.mjs', require: './index.js'}}}, ['index.js', 'browser.js', 'wrapper.mjs']),
    ...pkg('nav-lib', {exports: {'.': {ios: './ios.js', android: './android.js', default: './default.js'}}}, ['ios.js', 'android.js', 'default.js']),
    ...pkg('multi', {exports: {'.': {'react-native': './native.js', browser: './browser.js', node: './node.js', default: './default.js'}}}, ['native.js', 'browser.js', 'node.js', 'default.js']),
    ...pkg('redir', {exports: {'.': {node: './node.js', default: './default.js'}}, browser: {'./node.js': './browser.js'}}, ['node.js', 'default.js', 'browser.js']),
    ...pkg('uses-fs', {main: 'index.js', browser: {fs: false}}, ['index.js']),
  }),
  originModulePath: '/root/app/index.js',
  unstable_enablePackageExports: true,
};
const run = (ctx, name, platform, origin) => {
  try {
    const r = Resolver.resolve({...base, ...ctx, ...(origin && {originModulePath: origin})}, name, platform);
    return r.type === 'sourceFile' ? path.relative(nm, r.filePath) : r.type;
  } catch (e) {
    return e.constructor.name;
  }
};

// Framework config: runtime facts plus a user's platform UI facts.
const mainFields = ['react-native', 'browser', 'main'];
const top = {
  unstable_conditionNames: [],
  unstable_conditionsByPlatform: {ios: ['react-native', 'ios'], android: ['react-native', 'android'], web: ['browser']},
  mainFields,
};
const envConditions = {'react-server': ['node', 'react-server'], ssr: ['node']};
const strip = byPlatform => Object.fromEntries(Object.entries(byPlatform).map(([p, cs]) => [p, cs.filter(c => c !== 'browser' && c !== 'react-native')]));

const designs = {
  // The drafted map: adds to everything at the top level.
  'draft (additive)': env => ({...top, environment: env, unstable_conditionsByEnvironment: envConditions}),
  // Expo today, and a field override written as a value.
  'replace / override value': env => (env ? {...top, unstable_conditionNames: envConditions[env], unstable_conditionsByPlatform: {}} : top),
  // A field override written as a function of the inherited value.
  'override function': env => (env ? {...top, unstable_conditionNames: envConditions[env], unstable_conditionsByPlatform: strip(top.unstable_conditionsByPlatform)} : top),
  // Additive, with runtime facts on an addressable client entry.
  'additive + client': env => {
    const entry = env ? {names: envConditions[env], byPlatform: {}} : {names: [], byPlatform: {web: ['browser'], ios: ['react-native'], android: ['react-native']}};
    const ui = {ios: ['ios'], android: ['android']};
    const byPlatform = Object.fromEntries(['ios', 'android', 'web'].map(p => [p, [...(ui[p] ?? []), ...(entry.byPlatform[p] ?? [])]]));
    return {...top, unstable_conditionNames: entry.names, unstable_conditionsByPlatform: byPlatform};
  },
};

const cases = [
  [undefined, 'ios', 'multi'],
  [undefined, 'ios', 'nav-lib'],
  ['ssr', 'web', 'ws'],
  ['react-server', 'web', 'multi'],
  ['react-server', 'ios', 'nav-lib'],
  ['react-server', 'ios', 'multi'],
];
console.log(['bundle', 'package', ...Object.keys(designs)].join(' | '));
for (const [env, platform, name] of cases) {
  console.log([`${env ?? 'client'} ${platform}`, name, ...Object.values(designs).map(d => run(d(env), name, platform))].join(' | '));
}

// React Native's default config puts `react-native` in the global list.
const rn = {unstable_conditionNames: ['react-native'], unstable_conditionsByPlatform: {web: ['browser']}, mainFields};
console.log('RN defaults, draft, react-server web multi |', run({...rn, environment: 'react-server', unstable_conditionsByEnvironment: envConditions}, 'multi', 'web'));

// The "browser" main field in a server bundle whose conditions are already right.
const server = {unstable_conditionNames: ['node'], unstable_conditionsByPlatform: {}};
for (const fields of [['browser', 'main'], ['main']]) {
  console.log(`ssr web, mainFields ${JSON.stringify(fields)} | redir:`, run({...server, mainFields: fields}, 'redir', 'web'), '| fs from uses-fs:', run({...server, mainFields: fields}, 'fs', 'web', `${nm}/uses-fs/index.js`));
}

// Object.prototype keys from a bundle URL.
for (const [environment, platform] of [['constructor', 'ios'], ['toString', 'ios'], [undefined, 'constructor']]) {
  console.log(`environment=${environment} platform=${platform} |`, run({...designs['draft (additive)'](environment)}, 'multi', platform));
}
mergeConfig script
// Checks how metro-config's mergeConfig composes map-valued resolver options.
// Usage: BABEL_DISABLE_CACHE=1 node merge.js <metro checkout>
'use strict';
const path = require('node:path');
const METRO = process.argv[2];
require(path.join(METRO, 'packages/metro-babel-register')).unstable_registerForMetroMonorepo();
const {mergeConfig} = require(path.join(METRO, 'packages/metro-config/src/loadConfig.js'));
const {default: getDefaultConfig} = require(path.join(METRO, 'packages/metro-config/src/defaults/index.js'));

(async () => {
  const defaults = await getDefaultConfig('/tmp/project');
  const show = (label, value) => console.log(label.padEnd(58), JSON.stringify(value));

  show('defaults unstable_conditionsByPlatform', defaults.resolver.unstable_conditionsByPlatform);
  show('defaults unstable_conditionNames', defaults.resolver.unstable_conditionNames);
  show('defaults resolverMainFields', defaults.resolver.resolverMainFields);
  show('defaults unstable_conditionsByEnvironment', defaults.resolver.unstable_conditionsByEnvironment);

  const framework = {
    resolver: {
      unstable_conditionsByEnvironment: {'react-server': ['react-server'], node: ['node']},
      environments: {'react-server': {unstable_conditionNames: ['react-server']}},
    },
    environments: {'react-server': {resolver: {unstable_conditionNames: ['react-server']}}},
  };
  const user = {
    resolver: {
      unstable_conditionsByEnvironment: {worker: ['worker']},
      environments: {worker: {unstable_conditionNames: ['worker']}},
    },
    environments: {worker: {resolver: {}}},
  };
  const merged = mergeConfig(defaults, framework, user);
  show('framework+user: unstable_conditionsByEnvironment', merged.resolver.unstable_conditionsByEnvironment);
  show('framework+user: resolver.environments', merged.resolver.environments);
  show('framework+user: top-level environments', merged.environments);

  const macos = mergeConfig(defaults, {resolver: {unstable_conditionsByPlatform: {macos: ['react-native']}}});
  show('user sets {macos}: unstable_conditionsByPlatform', macos.resolver.unstable_conditionsByPlatform);

  const scheme = mergeConfig(defaults, {resolver: {schemeResolvers: {a: () => null}}}, {resolver: {schemeResolvers: {b: () => null}}});
  show('schemeResolvers keys after two layers', Object.keys(scheme.resolver.schemeResolvers));
})().catch(e => {
  console.error(e);
  process.exit(1);
});