Reputation: 31
The below code show an error in the Next.js project.
Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Type 'NextApiRequest' is missing the following properties from type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>': get, header, accepts, acceptsCharsets, and 29 more.ts(2345)
import session from 'express-session'
import connectMongo from 'connect-mongo'
import type { NextApiRequest, NextApiResponse } from 'next'
const MongoStore = connectMongo(session)
export default function sessionMiddleware(req: NextApiRequest, res: NextApiResponse, next: any) {
const mongoStore = new MongoStore({
client: req.dbClient,
stringify: false,
})
return session({
secret: process.env.SESSION_SECRET ?? '',
resave: false,
saveUninitialized: false,
store: mongoStore,
})(req, res, next)
}
Any solution for the above problem.
Upvotes: 5
Views: 7403
Reputation: 29
Blockquote
My solution to the problem is using type union https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html
import { RequestHandler, Request, Response } from 'express';
import { NextApiRequest, NextApiResponse } from 'next';
type NextApiRequestWithFormData = NextApiRequest &
Request & {
files: any[];
};
type NextApiResponseCustom = NextApiResponse & Response;
export default function initMiddleware(middleware: RequestHandler) {
return (
req: NextApiRequestWithFormData,
res: NextApiResponseCustom
): Promise<any> =>
new Promise((resolve, reject) => {
middleware(req, res, (result: any) => {
if (result instanceof Error) {
return reject(result);
}
return resolve(result);
});
});
}
the following code should work for you
import { RequestHandler, Request, Response } from 'express';
import { NextApiRequest, NextApiResponse } from 'next';
type NextApiRequestWithFormData = NextApiRequest &
Request & {
files: any[];
};
type NextApiResponseCustom = NextApiResponse & Response;
Upvotes: 2