更新所有依赖后NextJS处理器出现Next-Connect调用错误
问题
更新项目所有依赖包后,原本可正常运行的基于next-connect的NextJS API路由处理器代码出现TypeScript错误。错误代码为2349,提示「该表达式不可调用,类型'typeof import("/XXXX/node_modules/next-connect/dist/types/index")'无调用签名」,报错位置为调用nc处。此前代码运行正常,其余依赖更新引发的问题已修复,仅该问题未解决。
相关代码:
import cookieSession from 'cookie-session'; import { NextApiRequest, NextApiResponse } from 'next'; import nc from 'next-connect'; import { error } from 'next/dist/build/output/log'; import passport from './passport'; import { trustProxyMiddleware } from './trust-proxy-middleware'; export interface Request extends NextApiRequest { // Passport adds these to the request object logout: () => void; logIn: (user: Express.User, done: (err?: any) => void) => void; user?: Express.User; protocol?: string; } const COOKIE_SECRET = process.env.COOKIE_SECRET; /** * Create an API route handler with next-connect and all the necessary middlewares * * @example * ```ts * export default handler().get((req, res) => { ... }) * ``` */ function handler() { if (!COOKIE_SECRET) throw new Error(`Please add COOKIE_SECRET to your .env.local file!`); return ( nc<Request, NextApiResponse>({ onError: (err: any, _: any, res: NextApiResponse) => { error(err); res.status(500).end(err.toString()); }, }) // In order for authentication to work on Vercel, req.protocol needs to be set correctly. // However, Vercel's and Netlify's reverse proxy setup breaks req.protocol, which the custom // trustProxyMiddleware fixes again. .use(trustProxyMiddleware) .use( cookieSession({ name: 'session', keys: [COOKIE_SECRET], maxAge: 24 * 60 * 60 * 1000 * 30, // Do not change the lines below, they make cy.auth() work in e2e tests secure: process.env.NODE_ENV !== 'development' && !process.env.INSECURE_AUTH, signed: process.env.NODE_ENV !== 'development' && !process.env.INSECURE_AUTH, }), ) .use(passport.initialize()) .use(passport.session()) ); } export default handler;
错误详情:
[{"resource":"XXXX/server/api-route.ts","owner":"typescript","code":"2349","severity":8,"message":"该表达式不可调用。\n 类型'typeof import(\"/XXXX/node_modules/next-connect/dist/types/index\")'没有调用签名。","source":"ts","startLineNumber":32,"startColumn":3,"endLineNumber":32,"endColumn":5}]
解决方案
- 调整导入语句:next-connect版本升级后导出结构可能变化,尝试将导入从
import nc from 'next-connect'改为import { nc } from 'next-connect',或者直接导入实现文件:import nc from 'next-connect/dist/index.js',避免导入类型模块而非可调用函数。 - 适配新版本初始化写法:新版本对配置传递方式可能有调整,可拆分初始化步骤:
const router = nc<Request, NextApiResponse>(); router.onError((err, _, res) => { error(err); res.status(500).end(err.toString()); }); // 后续链式调用use、get等方法 - 检查版本兼容性:确认next-connect与当前Next.js版本是否兼容,若差异过大,可降级next-connect至此前可用版本,或查看官方更新文档,按新API规范修改代码。
内容的提问来源于stack exchange,提问作者JakeyX
相关产品推荐
相关产品推荐

