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)
const invalidServerComponentReactHooks = [
'useDeferredValue',
'useEffect',
'useImperativeHandle',
'useInsertionEffect',
'useLayoutEffect',
'useReducer',
'useRef',
'useState',
'useSyncExternalStore',
'useTransition',
]
function setMessage(error: Error, message: string): void {
error.message = message
if (error.stack) {
const lines = error.stack.split('\n')
lines[0] = message
error.stack = lines.join('\n')
}
}
export function formatServerError(error: Error): void { export function formatServerError(error: Error): void {
if (error.message.includes('createContext is not a function')) { if (error.message.includes('createContext is not a function')) {
const message = 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' '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'
error.message = message )
if (error.stack) { return
const lines = error.stack.split('\n') }
lines[0] = message
error.stack = lines.join('\n') 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 () => { files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
next = await createNext({ dependencies: {
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')), react: 'latest',
dependencies: { 'react-dom': 'latest',
react: 'latest', },
'react-dom': 'latest', skipStart: true,
}, },
skipStart: true, ({ next }) => {
}) describe('createContext called in Server Component', () => {
}) it('should show error when React.createContext is called', async () => {
afterAll(() => next.destroy()) const { session, cleanup } = await sandbox(
next,
describe('createContext called in Server Component', () => { new Map([
it('should show error when React.createContext is called', async () => { [
const { session, cleanup } = await sandbox( 'app/page.js',
next, `
new Map([
[
'app/page.js',
`
import React from 'react' import React from 'react'
const Context = React.createContext() const Context = React.createContext()
export default function Page() { export default function Page() {
...@@ -39,47 +34,47 @@ describe('Error Overlay for server components', () => { ...@@ -39,47 +34,47 @@ describe('Error Overlay for server components', () => {
</> </>
) )
}`, }`,
], ],
]) ])
)
expect(await session.hasRedbox(true)).toBe(true)
await check(async () => {
expect(await session.getRedboxSource(true)).toContain(
`TypeError: 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 'success'
}, 'success')
expect(next.cliOutput).toContain(
'createContext only works in Client Components'
)
await cleanup() expect(await session.hasRedbox(true)).toBe(true)
}) await check(async () => {
expect(await session.getRedboxSource(true)).toContain(
`TypeError: 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 'success'
}, 'success')
expect(next.cliOutput).toContain(
'createContext only works in Client Components'
)
it('should show error when React.createContext is called in external package', async () => { await cleanup()
const { session, cleanup } = await sandbox( })
next,
new Map([ it('should show error when React.createContext is called in external package', async () => {
[ const { session, cleanup } = await sandbox(
'node_modules/my-package/index.js', next,
` new Map([
[
'node_modules/my-package/index.js',
`
const React = require('react') const React = require('react')
module.exports = React.createContext() module.exports = React.createContext()
`, `,
], ],
[ [
'node_modules/my-package/package.json', 'node_modules/my-package/package.json',
` `
{ {
"name": "my-package", "name": "my-package",
"version": "0.0.1" "version": "0.0.1"
} }
`, `,
], ],
[ [
'app/page.js', 'app/page.js',
` `
import Context from 'my-package' import Context from 'my-package'
export default function Page() { export default function Page() {
return ( return (
...@@ -90,49 +85,49 @@ describe('Error Overlay for server components', () => { ...@@ -90,49 +85,49 @@ describe('Error Overlay for server components', () => {
</> </>
) )
}`, }`,
], ],
]) ])
) )
expect(await session.hasRedbox(true)).toBe(true) expect(await session.hasRedbox(true)).toBe(true)
await check(async () => { await check(async () => {
expect(await session.getRedboxSource(true)).toContain( expect(await session.getRedboxSource(true)).toContain(
`TypeError: 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` `TypeError: 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 'success' return 'success'
}, 'success') }, 'success')
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
'createContext only works in Client Components' 'createContext only works in Client Components'
) )
await cleanup() await cleanup()
}) })
it('should show error when createContext is called in external package', async () => { it('should show error when createContext is called in external package', async () => {
const { session, cleanup } = await sandbox( const { session, cleanup } = await sandbox(
next, next,
new Map([ new Map([
[ [
'node_modules/my-package/index.js', 'node_modules/my-package/index.js',
` `
const { createContext } = require('react') const { createContext } = require('react')
module.exports = createContext() module.exports = createContext()
`, `,
], ],
[ [
'node_modules/my-package/package.json', 'node_modules/my-package/package.json',
` `
{ {
"name": "my-package", "name": "my-package",
"version": "0.0.1" "version": "0.0.1"
} }
`, `,
], ],
[ [
'app/page.js', 'app/page.js',
` `
import Context from 'my-package' import Context from 'my-package'
export default function Page() { export default function Page() {
return ( return (
...@@ -143,23 +138,158 @@ describe('Error Overlay for server components', () => { ...@@ -143,23 +138,158 @@ describe('Error Overlay for server components', () => {
</> </>
) )
}`, }`,
], ],
]) ])
) )
expect(await session.hasRedbox(true)).toBe(true)
expect(await session.hasRedbox(true)).toBe(true) await check(async () => {
expect(await session.getRedboxSource(true)).toContain(
`TypeError: 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 'success'
}, 'success')
expect(next.cliOutput).toContain(
'createContext only works in Client Components'
)
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')
await check(async () => { expect(next.cliOutput).toContain(
expect(await session.getRedboxSource(true)).toContain( 'useEffect only works in Client Components'
`TypeError: 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 'success'
}, 'success')
expect(next.cliOutput).toContain( await cleanup()
'createContext 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