javascriptnext.jsmiddleware

How do i use server-only functions in Next.js middleware?


I am using Next.js 13 with the App Router.

When trying to import a server-only fetch function into middleware.js, I get the following error message:

Error: This module cannot be imported from a Client Component module. It should only be used from a Server Component. This error happened while generating the page. Any console logs will be displayed in the terminal window.

That seems odd, because middleware is executed on the server and so is 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 not allow a server-only function to be imported into middleware?


Solution

  • This has been fixed in v13.4.20-canary.39. You just need to install the latest version.
    Related discussion: middleware.ts treated as a client side component.