'How to use Hook inside Nextjs middleware?
I have a middleware like this
import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { useCheckIsAdminQuery } from "../../generated/graphql";
export function middleware(req: NextRequest, ev: NextFetchEvent) {
const {data,loading,error} = useCheckIsAdminQuery()
if(data?.checkIsAdmin){
return NextResponse.next()
}else{
const url = req.nextUrl.clone()
url.pathname = '/404'
return NextResponse.redirect(url)
}
}
useCheckIsQuery() just a hook was generated by codegen package, but I cannot call this hook inside middleware. The error display
Invalid hook call. Hooks can only be called inside of the body of a function component.
How can i fix it?
Solution 1:[1]
According to React docs: "Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.".
Nextjs' middleware is not a React function, so you cannot use hooks inside it. The solution to your problem is to create a hook with your custom logic, and manually calling it in the page you'd like to take effect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Enfield li |
