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

Improve errors caused by Next.js client hook called in a server component (#44588)

Throws if any of the Next.js client hooks are used in a server component in DEV.

```
Error: useSearchParams 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
```

Fixes NEXT-287

## 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 08c95302
import React from 'react'
export function clientHookInServerComponentError(
hookName: string
): void | never {
if (process.env.NODE_ENV !== 'production') {
// If useState is undefined we're in a server component
if (!React.useState) {
throw new Error(
`${hookName} 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`
)
}
}
}
......@@ -13,6 +13,7 @@ import {
// LayoutSegmentsContext,
} from '../../shared/lib/hooks-client-context'
import { bailoutToClientRendering } from './bailout-to-client-rendering'
import { clientHookInServerComponentError } from './client-hook-in-server-component-error'
const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol(
'internal for urlsearchparams readonly'
......@@ -70,6 +71,7 @@ class ReadonlyURLSearchParams {
* Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
*/
export function useSearchParams() {
clientHookInServerComponentError('useSearchParams')
const searchParams = useContext(SearchParamsContext)
const readonlySearchParams = useMemo(() => {
......@@ -92,19 +94,16 @@ export function useSearchParams() {
* Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard"
*/
export function usePathname(): string | null {
clientHookInServerComponentError('usePathname')
return useContext(PathnameContext)
}
// TODO-APP: getting all params when client-side navigating is non-trivial as it does not have route matchers so this might have to be a server context instead.
// export function useParams() {
// clientHookInServerComponentError('useParams')
// return useContext(ParamsContext)
// }
// TODO-APP: define what should be provided through context.
// export function useLayoutSegments() {
// return useContext(LayoutSegmentsContext)
// }
export {
ServerInsertedHTMLContext,
useServerInsertedHTML,
......@@ -114,6 +113,7 @@ export {
* Get the router methods. For example router.push('/dashboard')
*/
export function useRouter(): import('../../shared/lib/app-router-context').AppRouterInstance {
clientHookInServerComponentError('useRouter')
const router = useContext(AppRouterContext)
if (router === null) {
throw new Error('invariant expected app router to be mounted')
......@@ -161,6 +161,7 @@ function getSelectedLayoutSegmentPath(
export function useSelectedLayoutSegments(
parallelRouteKey: string = 'children'
): string[] {
clientHookInServerComponentError('useSelectedLayoutSegments')
const { tree } = useContext(LayoutRouterContext)
return getSelectedLayoutSegmentPath(tree, parallelRouteKey)
}
......@@ -172,6 +173,7 @@ export function useSelectedLayoutSegments(
export function useSelectedLayoutSegment(
parallelRouteKey: string = 'children'
): string | null {
clientHookInServerComponentError('useSelectedLayoutSegment')
const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey)
if (selectedLayoutSegments.length === 0) {
return null
......
......@@ -291,5 +291,47 @@ createNextDescribe(
await cleanup()
})
})
describe('Next.js component hooks called in Server Component', () => {
it.each([
// TODO-APP: add test for useParams
// ["useParams"],
['useRouter'],
['useSearchParams'],
['useSelectedLayoutSegment'],
['useSelectedLayoutSegments'],
['usePathname'],
])('should show error when %s is called', async (hook: string) => {
const { session, cleanup } = await sandbox(
next,
new Map([
[
'app/page.js',
`
import { ${hook} } from 'next/navigation'
export default function Page() {
${hook}()
return "Hello world"
}`,
],
])
)
expect(await session.hasRedbox(true)).toBe(true)
await check(async () => {
expect(await session.getRedboxSource(true)).toContain(
`Error: ${hook} 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(
`${hook} 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