#Middleware

1 messages · Page 1 of 1 (latest)

vagrant patio
#

Error: Cannot find the middleware module

Why do i have this error ?

cunning mapleBOT
#

Hi @vagrant patio. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources, there are several possible reasons why you might be encountering the "Cannot find the middleware module" error in NextJS:

  1. Incorrect file placement: Your middleware file should be placed at the root level of your project, at the same level as your app or pages directory (even if you're using a src directory). The file should be named middleware.ts or middleware.js Edge Middleware API Reference.

  2. Incorrect matcher configuration: If you're using a matcher in your middleware configuration, there might be an issue with your regex pattern. One user reported fixing their middleware by correcting their matcher regex Github Issue: middleware is not used in production with custom server.

  3. Module resolution issues: You might be trying to use a Node.js module in an Edge Function, which isn't supported. The Edge runtime only supports a subset of Web APIs MIDDLEWARE_INVOCATION_FAILED.

  4. ESM compatibility issues: If you're using ESM modules ("type": "module" in your package.json), there might be issues with how modules are resolved in middleware Github Issue: Cache handler ERR_MODULE_NOT_FOUND when using ESM modules.

  5. Incompatibility with output: 'export': If you're using output: 'export' in your Next.js config, middleware won't work in Next.js 14+ (though it did work in Next.js 13) Github Issue: Middleware + output: 'export' is no longer working from Next 13+.

#
  1. Recent bug in newer versions: There's an open issue in Next.js 15.1.6 where creating a middleware file causes a ReferenceError: __import_unsupported is not defined error Github Issue: [Error [ReferenceError]: __import_unsupported is not defined] after creating a middleware file.

To troubleshoot, check that:

  • Your middleware file is correctly placed
  • You're not using Node.js-specific modules in Edge middleware
  • Your matcher configuration is correct (if using one)
  • You're not using output: 'export' with middleware in Next.js 14+

If you could share more details about your specific setup and the exact error message, I could provide more targeted assistance.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@vagrant patio Kapa.ai is still learning and improving, please let me know how I did by reacting below.

vagrant patio
#

@cunning maple

import { NextRequest, NextResponse } from "next/server";
import { headers } from "next/headers";
import { auth } from "@/lib/auth";
 
export async function middleware(request: NextRequest) {
    const session = await auth.api.getSession({
        headers: await headers()
    })
 
    if(!session) {
        return NextResponse.redirect(new URL("/", request.url));
    }
 
    return NextResponse.next();
}
 
export const config = {
  runtime: "nodejs",
  matcher: ["/dashboard"], // Apply middleware to specific routes
};```

And it inside /src/middleware.ts
cunning mapleBOT
#

Let me check the knowledge base for you again. Give me one moment! :books:

#

Based on your code and the error you're experiencing, I can identify a few potential issues with your middleware implementation:

File Location

Your middleware file is correctly placed at /src/middleware.ts, which is at the same level as your app or pages directory if you're using the src directory structure. This follows the Next.js convention for middleware placement Middleware Convention.

Node.js Runtime Configuration

You're using the experimental Node.js runtime for middleware with runtime: "nodejs" in your config. This is a new feature available in Next.js v15.2 (canary) and requires additional configuration in your next.config.js file:

import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  experimental: {
    nodeMiddleware: true,
  },
}
 
export default nextConfig

Without this configuration, Next.js will throw an error Runtime.

Potential Issues

  1. Missing experimental flag: If you haven't added the nodeMiddleware: true flag to your next.config.js, this will cause an error.

  2. Version compatibility: The Node.js runtime for middleware is only available in Next.js v15.2 canary. If you're using a stable release, you'll get an error Runtime.

  3. Server-only imports: There's a known issue with server-only imports in middleware when using the Node.js runtime. If any of your imports (like your auth library) use server-only, this could cause problems Github Issue: server-only imports don't work with middleware and runtime nodejs.

#
  1. Headers API usage: You're using headers() from next/headers which might not be compatible with middleware. Middleware typically uses the request object directly to access headers.

Suggested Fix

Try modifying your middleware to use the request headers directly instead of the headers() API:

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
 
export async function middleware(request: NextRequest) {
    const session = await auth.api.getSession({
        headers: request.headers
    })
 
    if(!session) {
        return NextResponse.redirect(new URL("/", request.url));
    }
 
    return NextResponse.next();
}
 
export const config = {
  runtime: "nodejs",
  matcher: ["/dashboard"],
};

Also, ensure you've added the experimental flag to your next.config.js file and that you're using a compatible Next.js version.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: