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.
Summary
unstable_conditionsByEnvironment. All three analyses prefer it.target means language level or build output in most neighbouring tools. All three.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
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.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.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.resolver.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.
| Platform | Environment | |
|---|---|---|
| Question it answers | What does this output render for? | What runs this code, and on which side of the server/client boundary? |
| Values | ios, android, web, out-of-tree platforms | Unset (the client), react-server, an SSR environment (Expo calls it node) |
| Declared | resolver.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 conditions | Runtime conditions (node, workerd), role conditions (react-server), polyfills, the prelude, proxy transforms |
| Reaches, after step 1 | Transform options, graph ID, its own resolution cache level, getPolyfills({platform}), getTransformOptions | Transform 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
| Tool | Option | Values | What it sets |
|---|---|---|---|
| webpack | target | web, node, webworker, Electron and others, and also es5, es2020 and browserslist | The browser, node or worker condition, and main fields browser, module, main for web or module, main otherwise (docs) |
| esbuild | platform | browser, node, neutral | The browser or node condition, and main fields (docs) |
| Bun | target | browser, bun, node | "The intended execution environment for the bundle", preferring the browser or node condition (docs) |
| Parcel | A target's context | node, browser, web-worker and others, plus react-server and react-client in its RSC recipe | The environment of the target's modules (RSC recipe) |
| Vite | Named environments, each with a consumer | client, 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
| Kind | Examples | Belongs to |
|---|---|---|
| Platform identity | ios, android, custom UI conditions | The platform, in every environment |
| Client runtime | browser on web, react-native on iOS and Android | The client environment, per platform |
| Server runtime | node, workerd, edge-light | Server environments |
| React role | react-server | The react-server environment |
| Project | development, a monorepo source condition | Every bundle (the top level) |
| Module format | import, require, default | Metro, 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.
| Shape | Keeps browser out of web SSR | Keeps platform conditions in servers | Per-environment main fields | Can name the client | New ResolutionContext field | Analyses |
|---|---|---|---|---|---|---|
(a) unstable_conditionsByEnvironment, additive (the draft) | No | Yes | No | No | Yes | Closest to today. None recommends it as step 2. |
| (b) The same map, replacing | Yes | No | No | No | Yes | Rejected by all |
(c) One …ByEnvironment map per option | As (a) or (b) | As (a) or (b) | Yes | No | Several | Rejected by all |
(d) Top-level environments with resolver, transformer, serializer | Depends on semantics | Depends | Yes | Yes | Depends | Rejected by all |
(e) resolver.unstable_environments: a value replaces, a function computes | Yes | Only in the function form | Yes, per platform through a function | No, it's an error | No | Recommended by A |
(e′) resolver.unstable_environments: conditions add, lists replace, client entry | Yes, once browser is on client | Yes | Yes, one list per environment | Yes | No | Recommended by B and C |
(f) A hook such as getEnvironmentOptions({platform, environment}) | Yes | Yes | Yes | Yes | No | Rejected 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,assetExtsandadditionalExtstogether (createFileMap.js), so an environment can reorder or narrowsourceExtsbut 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 asoptions.environmentandcaller.environment, and Expo varies its transforms that way. - The serializer. Its per-bundle variation points,
getPolyfillsandgetModulesRunBeforeMainModule, 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-environmentcreateModuleIdFactoryis 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 A | Analysis B | Analysis C | |
|---|---|---|---|
| Conditions in an entry | Replace, or computed by a function | Add | Add |
| Main fields in an entry | Replace, or a per-platform function | Replace | Replace |
sourceExts in an entry | Yes, within the crawled set | Later, within the crawled set | No, leave it to resolveRequest |
A client entry | A config error | Applies to unset | Applies to unset |
How browser leaves server bundles | Each server entry removes it | It moves to the client entry | It moves to the client entry |
Resolver results under each design
| Bundle | Package | Draft (additive) | Replace, or override value | Override function | Add, with client entry |
|---|---|---|---|---|---|
| Client, iOS | multi | native.js | native.js | native.js | native.js |
| Client, iOS | nav-lib | ios.js | ios.js | ios.js | ios.js |
| SSR, web | ws | browser.js | index.js | index.js | index.js |
react-server, web | multi | browser.js | node.js | node.js | node.js |
react-server, iOS | nav-lib | ios.js | default.js | ios.js | ios.js |
react-server, iOS | multi | native.js | node.js | node.js | node.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 node | Main fields browser, main | Main fields main |
|---|---|---|
exports: {node, default} with browser: {"./node.js": "./browser.js"} | browser.js | node.js |
fs from a package with browser: {fs: false} | The empty module | Not replaced |
Which options vary per environment
| Option | Per environment? | Mechanism |
|---|---|---|
unstable_conditionNames, unstable_conditionsByPlatform | Yes (all three) | Entry fields that add to the top level |
resolverMainFields | Yes (all three) | An entry field that replaces. Per-platform values are open. |
sourceExts | Open: A yes, B later, C no | Expo only moves .mjs after .js for servers (L833). If added, it has to stay within the crawled set. |
platforms, platform extensions, assetExts | No (all three) | Crawl-time and server-wide. Expo varies asset output by environment through transform options instead. |
preferNativePlatform | No (all three) | A platform fact, hard-coded today. Expo sets platform !== 'web' for every environment (L829). |
resolveRequest, schemeResolvers | No | Logic reads context.environment, from step 1 |
getTransformOptions | Yes (all three) | Add environment to its options (transformHelpers.js) |
getPolyfills | Yes (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. |
getModulesRunBeforeMainModule | Yes (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 config | No (all three) | Hashed once; transformers branch on options.environment |
| Custom serializers | No new config | They read graph.transformOptions.environment |
createModuleIdFactory | Context, not config | The planned module ID context step |
Reporter bundleDetails | Yes (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.
| Candidate | Why not |
|---|---|
target | Babel'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). |
runtime | SSR and react-server share a runtime, so it mislabels the distinction that matters. It also collides with metro-runtime and Babel's runtime. |
consumer | In Vite it is a binary attribute of an environment, client or server (config.ts), not the dimension itself. |
layer | webpack's per-module tag within one compilation. It presumes per-module environment switching, which Metro's RSC design leaves open. |
context | ResolutionContext 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 today | Ideal, achievable in months | |
|---|---|---|
| Step 1 | As it is, plus environment=client normalised to unset | The same |
| Step 2 | The drafted resolver.unstable_conditionsByEnvironment, additive, with own-property lookups | resolver.unstable_environments: conditions add, resolverMainFields replaces, a client entry, merged by environment then field, own-property lookups and allowlisted keys |
| Hooks | environment for getTransformOptions and getPolyfills, and an optional second argument for getModulesRunBeforeMainModule | The same, plus bundleDetails, Metro.buildGraph and runBuild, and metro build --environment |
Keeps browser out of web SSR | Only through resolveRequest | Through config |
| Expo's server override | Stays whole (L832–872) | Conditions move to config. Per-platform main fields, .mjs order and preferNativePlatform stay. |
| Later breaking release | Nothing to flip, but the draft becomes an overlapping option to retire | Metro's default browser moves to the client entry. The family drops unstable_, and possibly becomes conditions. |
| Size | 22 lines of source, excluding tests and docs | About 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
| Change | Metro users | React Native community CLI | Expo (pins Metro) |
|---|---|---|---|
Step 1, with client normalised | Nothing. 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 arguments | Nothing 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. | Nothing | Nothing. 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, closest | Nothing: the map defaults to {} | Nothing, but its global react-native condition reaches server bundles and config can't remove it | Nothing. It can move react-server into config, and keeps its override. |
| Step 2, ideal | Nothing: absent by default | Nothing: it defines no environments | Nothing. 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 client | Configs whose top-level unstable_conditionsByPlatform lacks web: ['browser'] get it back for web client bundles | Nothing: 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 rename | Every config that sets the condition options | @react-native/metro-config renames unstable_conditionNames in the React Native release that takes the Metro bump | Renames 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.
| Topic | Analysis A | Analysis B | Analysis C | Resolution |
|---|---|---|---|---|
| Agreed by all three | ||||
| Platform and environment | Separate 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 | ||
| Conditions | Come 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 family | A resolver-scoped, environment-major map computed in ModuleResolver. Reject (b), (c), (d) and (f). | Holds | ||
| Merging | mergeConfig replaces maps wholesale; the new map needs a by-environment merge | Holds; ran mergeConfig | ||
| Inheritance | Environments inherit the top level | Holds; Vite's non-inheritance broke vitest-dev/vitest#6992 | ||
| Main fields | Vary per environment and replace | Holds; browser field replacements reach server bundles | ||
client in URLs | Normalise environment=client to unset in step 1, before it ships | Holds | ||
| Hook arguments | environment for getTransformOptions, getPolyfills, getModulesRunBeforeMainModule. A and C put it in the near term, B in the ideal horizon. | Independent and additive; ship with either | ||
| Lookups | Own-property only, in the new map and in unstable_conditionsByPlatform | Holds; reproduced the TypeError | ||
| Name | Keep environment; reject target, runtime, consumer, layer, context | Holds | ||
| Split | ||||
| Semantics of an entry | A value replaces; a function computes | Conditions add; lists replace | Conditions add; lists replace | B and C hold for conditions: they compose with user additions, and A's value form doesn't |
A client entry | An error | Applies to unset | Applies to unset | B and C; it follows from adding |
| The draft as step 2 | Ship it only in the closest horizon; recommends (e) instead | Don't ship it as it is | Only if a react-server condition is needed before the shape is agreed | All prefer a structured map. The draft is a stopgap only. |
Default browser flip | Not needed under override | Flag, then flip | Flip; the map is the opt-in | Follows from adding. Recommended, flagged first. |
| Per-platform main fields | Function form | Not addressed; claims Expo can drop its whole override | Stays in resolvers; a platform-axis gap | Open. Recommend C, and widen to functions later if needed. |
sourceExts | Yes | Later | No | Open. Recommend deferring; Expo's only use is a reorder. |
| Container key | unstable_environments | environments | unstable_environments | Recommend the prefix (A and C) |
| Keys inside entries | Mirror, with unstable_ | Mirror, with unstable_ | Unprefixed | Recommend mirroring (A and B) |
conditions rename | At the unprefix release | Never | At the unprefix release | Open. Recommend renaming then (A and C). |
| Environment values | Name for roles | Document Expo's names | Name for roles | Docs use role names; values stay free-form |
| Raised by one or two | ||||
| Config-reading resolvers | Raised | Not raised | Raised, with the tvOS and macOS case | Accepted; inferred from code, not reproduced |
| Client-reference mismatch | Re-resolve each client reference in the client environment when building reference sets, and warn on a mismatch | Not raised | Notes the server's resolution decides | Worth adding to the reference-sets step |
| Unknown environment names | Not raised | Top level only; maybe warn | Unbounded values from URLs; defer declaring them | Open; defer |
react-native on native servers | Two owners | Expo drops the condition but keeps the main field | The framework decides by placement | The 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'sreact-serverand SSR main fields differ between web and native (L845–865), which one list per environment can't express, and itspreferNativePlatformoverride is per platform. - Analysis B: the flip breaks only configs that remove
browseron 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 isclient: {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
GetTransformOptionsOptsinexact 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 ismodule,node,development|production, and the client's ismodule,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.mjsafter.jsfor 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
conditionsrename. Recommendation: rename when the family dropsunstable_, 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=clientto unset in step 1, before it ships. - Land
resolver.unstable_environmentsas step 2 instead of the draftedunstable_conditionsByEnvironment: conditions add,resolverMainFieldsreplaces, acliententry, a merge by environment then field, own-property lookups and allowlisted keys. Fix the same lookup inunstable_conditionsByPlatform. - Pass
environmenttogetTransformOptionsandgetPolyfills, and as an optional second argument togetModulesRunBeforeMainModule. Add it tobundleDetails,Metro.buildGraphand the CLI. - Document the partition from day one: the top level holds facts for every bundle, and
clientholds client-runtime facts. Then flag, and flip in a breaking release, Metro's defaultbrowseronto thecliententry. - Keep the name
environment. Decide theconditionsrename when the family dropsunstable_. - 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);
});
Revisions
| Revision | Date | Change |
|---|---|---|
| 1 | 2026-11-22 | First published. |
Each revision links to a frozen copy of the report as it was published. The commit history has every edit.