简体   繁体   中英

Next.js13 MiddleWare occurs [TypeError: Class extends value undefined is not a constructor or null]

My Next.js project try middleware to ver13 occuring [TypeError: Class extends value undefined is not a constructor or null]. but when I try ver12. that is no error and working fine. Does anyone could helping me?

/middleware.ts

import { NextRequest, NextResponse } from 'next/server'

export const config = {
  matcher: ['/', '/index'],
}

export function middleware(req: NextRequest) {
  const basicAuth = req.headers.get('authorization')
  const url = req.nextUrl

  if (basicAuth) {
    const authValue = basicAuth.split(' ')[1]
    const [user, pwd] = atob(authValue).split(':')

    if (user === 'username' && pwd === 'password') {
      return NextResponse.next()
    }
  }
  url.pathname = '/api/auth'

  return NextResponse.rewrite(url)
}

/pages/api/auth.ts

import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(_: NextApiRequest, res: NextApiResponse) {
  res.setHeader('WWW-authenticate', 'Basic realm="Secure Area"')
  res.statusCode = 401
  res.end(`Auth Required.`)
}

terminal

error - Error [TypeError]: Class extends value undefined is not a constructor or null
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/file.js (evalmachine.<anonymous>:5724:19)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/formdata.js (evalmachine.<anonymous>:5881:49)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/body.js (evalmachine.<anonymous>:6094:35)
    at __require (evalmachine.<anonymous>:14:50)
    at ../../node_modules/.pnpm/undici@5.11.0/node_modules/undici/lib/fetch/response.js (evalmachine.<anonymous>:6510:49)
    at __require (evalmachine.<anonymous>:14:50)
    at <unknown> (evalmachine.<anonymous>:11635:30)
    at requireFn (file:///Users/tenrashuuji/projects/LyricMob_Next.js/node_modules/next/dist/compiled/edge-runtime/index.js:1:7079) {
  middleware: true
}

I try to Next.js ver12 with same code going to fine.

I ran into this issue myself, found an answer here https://github.com/redwoodjs/redwood/issues/6338

TLDR;

Upgrade to Node version 16*

This post below states that it should work with 16.4.0 or 16.8.0, I'm using 16.17.0 and it also works https://community.redwoodjs.com/t/moved-to-issue-tutorial-problem-typeerror-class-extends-value-undefined-is-not-a-constructor-or-null/3941

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM