nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
25k stars 3.53k forks source link

Middleware Throws Error with Lazy Init since 5.0.0-beta.20 #12267

Open MoscoviumAlchemist opened 2 days ago

MoscoviumAlchemist commented 2 days ago

Environment

  Binaries:
    Node: 20.16.0 - ~/.nvm/versions/node/v20.16.0/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    npm: 10.8.1 - ~/.nvm/versions/node/v20.16.0/bin/npm
    pnpm: 9.12.0 - /opt/homebrew/bin/pnpm
  npmPackages:
    @auth/core: ^0.37.4 => 0.37.4 
    next: 15.0.3 => 15.0.3 
    next-auth: ^5.0.0-beta.25 => 5.0.0-beta.25 
    react: 19.0.0-rc-69d4b800-20241021 => 19.0.0-rc-69d4b800-20241021 

Reproduction URL

https://github.com/MoscoviumAlchemist/nextjs-authjs-lazy-init-with-middleware/tree/lazy-init-middleware-bug

Describe the issue

⨯ Error: The Middleware "/middleware" must export a `middleware` or a `default` function at [project]/node_modules/next/dist/esm/build/templates/middleware.js { INNER_MIDDLEWARE_MODULE => "[project]/src/middleware.ts [middleware] (ecmascript)" } [middleware] (ecmascript) (.next/server/edge/chunks/_608f43._.js:11284:11) at <unknown> (.next/server/edge/chunks/edge-wrapper_8e4124.js:693:27) at runModuleExecutionHooks (.next/server/edge/chunks/edge-wrapper_8e4124.js:738:9) at instantiateModule (.next/server/edge/chunks/edge-wrapper_8e4124.js:691:9) at getOrInstantiateModuleFromParent (.next/server/edge/chunks/edge-wrapper_8e4124.js:624:12) at esmImport (.next/server/edge/chunks/edge-wrapper_8e4124.js:142:20) at <unknown> (.next/server/edge/chunks/_608f43._.js:11323:69)

How to reproduce

A) Clone the repository https://github.com/MoscoviumAlchemist/nextjs-authjs-lazy-init-with-middleware/tree/lazy-init-middleware-bug B) Add .env or .env.local file with:

AUTH_TRUST_HOST=true
AUTH_SECRET= # Linux: `openssl rand -hex 32` or go to https://generate-secret.vercel.app/32
DEBUG_AUTH_SESSIONS=false

C) Run the app by doing: npm run dev

Downgrading to 5.0.0-beta.19 the middleware won't throw errors, but since 5.0.0-beta.20 it throws

`Error: The Middleware "/middleware" must export a `middleware` or a `default` function`

Removing lazy init (by editing auth.ts to remove the request param) and the middleware also loads correctly.

Expected behavior

Middleware should export as nextjs expects even when next-auth lazy init is enabled.