Unverified Commit d89bdb2b authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Improve errors caused by client hook called in a server component (#44538)

Improve errors caused by client hook called in a server component.

Before
![image](https://user-images.githubusercontent.com/25056922/210399932-02d1071c-0d06-4260-8f1d-7da436e8bca9.png)


After
![image](https://user-images.githubusercontent.com/25056922/210399817-f949fb14-2f81-4309-bfcb-27af38ea1329.png)

Fixes NEXT-311

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 90b86be6
...@@ -777,6 +777,10 @@ ...@@ -777,6 +777,10 @@
{ {
"title": "context-in-server-component", "title": "context-in-server-component",
"path": "/errors/context-in-server-component.md" "path": "/errors/context-in-server-component.md"
},
{
"title": "react-client-hook-in-server-component",
"path": "/errors/react-client-hook-in-server-component.md"
} }
] ]
} }
......
# React client hook in Server Component
#### Why This Error Occurred
You are using a React client hook in a Server Component.
#### Possible Ways to Fix It
Mark the component using the hook as a Client Component by adding `'use client'` at the top of the file.
##### Before
```jsx
import { useEffect } from 'react'
export default function Page() {
useEffect(() => {
console.log('in useEffect')
})
return <p>Hello world</p>
}
```
##### After
```jsx
'use client'
import { useEffect } from 'react'
export default function Page() {
useEffect(() => {
console.log('in useEffect')
})
return <p>Hello world</p>
}
```
### Useful Links
[Server and Client Components](https://beta.nextjs.org/docs/rendering/server-and-client-components)
export function formatServerError(error: Error): void { const invalidServerComponentReactHooks = [
if (error.message.includes('createContext is not a function')) { 'useDeferredValue',
const message = 'useEffect',
'createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component' 'useImperativeHandle',
'useInsertionEffect',
'useLayoutEffect',
'useReducer',
'useRef',
'useState',
'useSyncExternalStore',
'useTransition',
]
function setMessage(error: Error, message: string): void {
error.message = message error.message = message
if (error.stack) { if (error.stack) {
const lines = error.stack.split('\n') const lines = error.stack.split('\n')
lines[0] = message lines[0] = message
error.stack = lines.join('\n') error.stack = lines.join('\n')
} }
}
export function formatServerError(error: Error): void {
if (error.message.includes('createContext is not a function')) {
setMessage(
error,
'createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component'
)
return
}
for (const clientHook of invalidServerComponentReactHooks) {
if (error.message.includes(`${clientHook} is not a function`)) {
setMessage(
error,
`${clientHook} only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`
)
return
}
} }
} }
...@@ -47,6 +47,7 @@ import { ...@@ -47,6 +47,7 @@ import {
} from '../client/components/app-router-headers' } from '../client/components/app-router-headers'
import type { StaticGenerationStore } from '../client/components/static-generation-async-storage' import type { StaticGenerationStore } from '../client/components/static-generation-async-storage'
import { DefaultHead } from '../client/components/head' import { DefaultHead } from '../client/components/head'
import { formatServerError } from '../lib/format-server-error'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -227,6 +228,10 @@ function createErrorHandler( ...@@ -227,6 +228,10 @@ function createErrorHandler(
return err.digest return err.digest
} }
// Format server errors in development to add more helpful error messages
if (process.env.NODE_ENV !== 'production') {
formatServerError(err)
}
// Used for debugging error source // Used for debugging error source
// console.error(_source, err) // console.error(_source, err)
console.error(err) console.error(err)
......
/* eslint-env jest */ /* eslint-env jest */
import { sandbox } from './helpers' import { sandbox } from './helpers'
import { createNext, FileRef } from 'e2e-utils' import { createNextDescribe, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import path from 'path' import path from 'path'
import { check } from 'next-test-utils' import { check } from 'next-test-utils'
describe('Error Overlay for server components', () => { createNextDescribe(
let next: NextInstance 'Error Overlay for server components',
{
beforeAll(async () => {
next = await createNext({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
dependencies: { dependencies: {
react: 'latest', react: 'latest',
'react-dom': 'latest', 'react-dom': 'latest',
}, },
skipStart: true, skipStart: true,
}) },
}) ({ next }) => {
afterAll(() => next.destroy())
describe('createContext called in Server Component', () => { describe('createContext called in Server Component', () => {
it('should show error when React.createContext is called', async () => { it('should show error when React.createContext is called', async () => {
const { session, cleanup } = await sandbox( const { session, cleanup } = await sandbox(
...@@ -162,4 +157,139 @@ describe('Error Overlay for server components', () => { ...@@ -162,4 +157,139 @@ describe('Error Overlay for server components', () => {
await cleanup() await cleanup()
}) })
}) })
})
describe('React component hooks called in Server Component', () => {
it('should show error when React.<client-hook> is called', async () => {
const { session, cleanup } = await sandbox(
next,
new Map([
[
'app/page.js',
`
import React from 'react'
export default function Page() {
const ref = React.useRef()
return "Hello world"
}`,
],
])
)
expect(await session.hasRedbox(true)).toBe(true)
await check(async () => {
expect(await session.getRedboxSource(true)).toContain(
`Error: useRef only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`
)
return 'success'
}, 'success')
expect(next.cliOutput).toContain(
'useRef only works in Client Components'
)
await cleanup()
})
it('should show error when React.<client-hook> is called in external package', async () => {
const { session, cleanup } = await sandbox(
next,
new Map([
[
'node_modules/my-package/index.js',
`
const React = require('react')
module.exports = function Component() {
const [state, useState] = React.useState()
return "Hello world"
}
`,
],
[
'node_modules/my-package/package.json',
`
{
"name": "my-package",
"version": "0.0.1"
}
`,
],
[
'app/page.js',
`
import Component from 'my-package'
export default function Page() {
return <Component />
}`,
],
])
)
expect(await session.hasRedbox(true)).toBe(true)
await check(async () => {
expect(await session.getRedboxSource(true)).toContain(
`Error: useState only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`
)
return 'success'
}, 'success')
expect(next.cliOutput).toContain(
'useState only works in Client Components'
)
await cleanup()
})
it('should show error when React client hook is called in external package', async () => {
const { session, cleanup } = await sandbox(
next,
new Map([
[
'node_modules/my-package/index.js',
`
const { useEffect } = require('react')
module.exports = function Component() {
useEffect(() => {}, [])
return "Hello world"
}
`,
],
[
'node_modules/my-package/package.json',
`
{
"name": "my-package",
"version": "0.0.1"
}
`,
],
[
'app/page.js',
`
import Component from 'my-package'
export default function Page() {
return <Component />
}`,
],
])
)
expect(await session.hasRedbox(true)).toBe(true)
await check(async () => {
expect(await session.getRedboxSource(true)).toContain(
`Error: useEffect only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/react-client-hook-in-server-component`
)
return 'success'
}, 'success')
expect(next.cliOutput).toContain(
'useEffect only works in Client Components'
)
await cleanup()
})
})
}
)
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