API 路由中的无效挂钩调用

我正在尝试使用 next-auth 保护 API 端点,但端点返回错误“无效的挂钩调用”

以下是 API 端点的完整代码:

import Sale from '../../../../models/Sale';
import dbConnect from '../../../../utils/dbConnect';
import { useSession, getSession } from 'next-auth/client'

export default async function handler({query: {number}}, res) {

  const [session, loading] = useSession()
  await dbConnect();

  if (typeof window !== 'undefined' && loading) return null

  if (!session) {
    return <p> Unauthorized </p>

  if (session) {
    const date = new Date();
    const currentYear = date.getFullYear();
    const firstYear = currentYear - number + 1;

    const sales = await Sale.find({
      orderYear: {
        $gte: firstYear
      subTotal: {
        $gt: 3000

    if (!sales || !sales.length) {
        error: 'No records found for date range'
    } else {
        data: {
          sales: sales,
          count: sales.length


export async function getServerSideProps(context) {
  const session = await getSession(context)
  return {
    props: {


Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.


我应该如何使用 useSession() 钩子?

stack overflow Invalid hook call in API route
author avatar


正如错误提示的那样,您只能在 React 功能组件中调用钩子。

这个函数不是一个 React 组件,它是一个 API 路由,就像你说的那样。我对 NextJS 不是很了解,但也许您需要的功能存在于其他地方。您从一个名为 next-auth/client 的库中导入它的事实有点引起怀疑。