Unverified Commit 2251d0f7 authored by Joseph's avatar Joseph Committed by GitHub
parent b268caea
......@@ -507,7 +507,7 @@ export default function Page() {
### Preventing environment poisoning
JavaScript modules can be shared between both Server and Client Components modules. This means it's possible to accidentanlly import server-only code into the client. For example, consider the following function:
JavaScript modules can be shared between both Server and Client Components modules. This means it's possible to accidentally import server-only code into the client. For example, consider the following function:
```ts filename="lib/data.ts" switcher
export async function getData() {
......@@ -541,10 +541,6 @@ As a result, even though `getData()` can be imported and executed on the client,
To prevent accidental usage in Client Components, you can use the [`server-only` package](https://www.npmjs.com/package/server-only).
```bash filename="Terminal"
npm install server-only
```
Then, import the package into a file that contains server-only code:
```js filename="lib/data.js"
......@@ -563,4 +559,26 @@ export async function getData() {
Now, if you try to import the module into a Client Component, there will be a build-time error.
> **Good to know**: The corresponding [`client-only` package](https://www.npmjs.com/package/client-only) can be used to mark modules that contain client-only logic like code that accesses the `window` object.
The corresponding [`client-only` package](https://www.npmjs.com/package/client-only) can be used to mark modules that contain client-only logic like code that accesses the `window` object.
In Next.js, installing `server-only` or `client-only` is **optional**. However, if your linting rules flag extraneous dependencies, you may install them to avoid issues.
```bash package="npm"
npm install server-only
```
```bash package="yarn"
yarn add server-only
```
```bash package="pnpm"
pnpm add server-only
```
```bash package="bun"
bun add server-only
```
Next.js handles `server-only` and `client-only` imports internally to provide clearer error messages when a module is used in the wrong environment. The contents of these packages from NPM are not used by Next.js.
Next.js also provides its own type declarations for `server-only` and `client-only`, for TypeScript configurations where [`noUncheckedSideEffectImports`](https://www.typescriptlang.org/tsconfig/#noUncheckedSideEffectImports) is active.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment