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 { ...@@ -13,6 +13,7 @@ import {
// LayoutSegmentsContext, // LayoutSegmentsContext,
} from '../../shared/lib/hooks-client-context' } from '../../shared/lib/hooks-client-context'
import { bailoutToClientRendering } from './bailout-to-client-rendering' import { bailoutToClientRendering } from './bailout-to-client-rendering'
import { clientHookInServerComponentError } from './client-hook-in-server-component-error'
const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol( const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol(
'internal for urlsearchparams readonly' 'internal for urlsearchparams readonly'
...@@ -70,6 +71,7 @@ class ReadonlyURLSearchParams { ...@@ -70,6 +71,7 @@ class ReadonlyURLSearchParams {
* Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams * Learn more about URLSearchParams here: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
*/ */
export function useSearchParams() { export function useSearchParams() {
clientHookInServerComponentError('useSearchParams')
const searchParams = useContext(SearchParamsContext) const searchParams = useContext(SearchParamsContext)
const readonlySearchParams = useMemo(() => { const readonlySearchParams = useMemo(() => {
...@@ -92,19 +94,16 @@ export function useSearchParams() { ...@@ -92,19 +94,16 @@ export function useSearchParams() {
* Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard" * Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard"
*/ */
export function usePathname(): string | null { export function usePathname(): string | null {
clientHookInServerComponentError('usePathname')
return useContext(PathnameContext) 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. // 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() { // export function useParams() {
// clientHookInServerComponentError('useParams')
// return useContext(ParamsContext) // return useContext(ParamsContext)
// } // }
// TODO-APP: define what should be provided through context.
// export function useLayoutSegments() {
// return useContext(LayoutSegmentsContext)
// }
export { export {
ServerInsertedHTMLContext, ServerInsertedHTMLContext,
useServerInsertedHTML, useServerInsertedHTML,
...@@ -114,6 +113,7 @@ export { ...@@ -114,6 +113,7 @@ export {
* Get the router methods. For example router.push('/dashboard') * Get the router methods. For example router.push('/dashboard')
*/ */
export function useRouter(): import('../../shared/lib/app-router-context').AppRouterInstance { export function useRouter(): import('../../shared/lib/app-router-context').AppRouterInstance {
clientHookInServerComponentError('useRouter')
const router = useContext(AppRouterContext) const router = useContext(AppRouterContext)
if (router === null) { if (router === null) {
throw new Error('invariant expected app router to be mounted') throw new Error('invariant expected app router to be mounted')
...@@ -161,6 +161,7 @@ function getSelectedLayoutSegmentPath( ...@@ -161,6 +161,7 @@ function getSelectedLayoutSegmentPath(
export function useSelectedLayoutSegments( export function useSelectedLayoutSegments(
parallelRouteKey: string = 'children' parallelRouteKey: string = 'children'
): string[] { ): string[] {
clientHookInServerComponentError('useSelectedLayoutSegments')
const { tree } = useContext(LayoutRouterContext) const { tree } = useContext(LayoutRouterContext)
return getSelectedLayoutSegmentPath(tree, parallelRouteKey) return getSelectedLayoutSegmentPath(tree, parallelRouteKey)
} }
...@@ -172,6 +173,7 @@ export function useSelectedLayoutSegments( ...@@ -172,6 +173,7 @@ export function useSelectedLayoutSegments(
export function useSelectedLayoutSegment( export function useSelectedLayoutSegment(
parallelRouteKey: string = 'children' parallelRouteKey: string = 'children'
): string | null { ): string | null {
clientHookInServerComponentError('useSelectedLayoutSegment')
const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey) const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey)
if (selectedLayoutSegments.length === 0) { if (selectedLayoutSegments.length === 0) {
return null return null
......
...@@ -291,5 +291,47 @@ createNextDescribe( ...@@ -291,5 +291,47 @@ createNextDescribe(
await cleanup() 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