Skip to content

Commit

Permalink
Restrict React DOM imports from Server Components
Browse files Browse the repository at this point in the history
Adds a separate entry point for the react-dom package when it's
accessed from a Server Component environment, using the "react-server"
export condition.

When you're inside a Server Component module, you won't be able to
import client-only APIs like useState. This applies to almost all React
DOM exports, except for Float ones like preload.
  • Loading branch information
acdlite committed Sep 15, 2023
1 parent d6dcad6 commit e240130
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
7 changes: 7 additions & 0 deletions packages/react-dom/npm/react-dom.shared-subset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-dom.shared-subset.production.min.js');
} else {
module.exports = require('./cjs/react-dom.shared-subset.development.js');
}
5 changes: 4 additions & 1 deletion packages/react-dom/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@
"umd/"
],
"exports": {
".": "./index.js",
".": {
"react-server": "./react-dom.shared-subset.js",
"default": "./index.js"
},
"./client": "./client.js",
"./server": {
"workerd": "./server.edge.js",
Expand Down
20 changes: 20 additions & 0 deletions packages/react-dom/src/ReactDOMSharedSubset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

// This is the subset of APIs that can be accessed from Server Component modules
export {default as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED} from './ReactDOMSharedInternals';
export {
prefetchDNS,
preconnect,
preload,
preloadModule,
preinit,
preinitModule,
version,
} from './client/ReactDOM';
12 changes: 12 additions & 0 deletions scripts/rollup/bundles.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,18 @@ const bundles = [
externals: ['react'],
},

/******* React DOM Shared Subset *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-dom/src/ReactDOMSharedSubset.js',
name: 'react-dom.shared-subset',
global: 'ReactDOM',
minifyWithProdErrorCodes: false,
wrapWithModuleBoundaries: false,
externals: ['react'],
},

/******* Test Utils *******/
{
moduleType: RENDERER_UTILS,
Expand Down

0 comments on commit e240130

Please sign in to comment.