In my current project, I am utilizing Next.js 13 along with the App Router feature.
While attempting to include a server-specific fetch function in middleware.js, an error message is encountered:
Error: Unable to import this module from a Client Component module. This module should only be accessed from a Server Component. This error occurred during page generation process. Any console logs will be displayed in the terminal window.
It is confusing because middleware runs on the server and so does the imported function.
middleware.js:
import { getClientData } from "@lib/getClientData";
export default async function middleware(req) { ... }
getClientData.js:
import "server-only";
export const getClientData = async () => {
const data = await ....
};
Why does Next.js restrict the importing of a server-only function into middleware?