The type 'NextApiRequest' lacks the following attributes compared to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

An error has been identified in the code for a Next.js project below.

The error message reads: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. Type 'NextApiRequest' is missing certain properties required by 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>', such as get, header, accepts, acceptsCharsets, and 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)
}

https://i.sstatic.net/Ei4x8.jpg

Any suggestions on how to resolve the issue mentioned above?

Answer №1

Blockquote

To tackle the issue at hand, I propose utilizing type union - a concept that can be explored further at 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);
      });
    });
}

You should find that the provided code is well-suited for your needs

import { RequestHandler, Request, Response } from 'express';
import { NextApiRequest, NextApiResponse } from 'next';

type NextApiRequestWithFormData = NextApiRequest &
  Request & {
    files: any[];
  };

type NextApiResponseCustom = NextApiResponse & Response;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do not display large numbers within an HTML card

I have https://i.sstatic.net/DkowD.png this card here and displaying dynamic data inside it. The number is quite large, so I would like it to appear as 0.600000+. If a user hovers over the number, a tooltip should display the full number. How can I achieve ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

The name 'Firebase' is not recognized by Typescript

Encountering typescript errors while building a project that incorporates angularfire2 and firebase. Here are the packages: "angularfire2": "^2.0.0-beta.0", "firebase": "^2.4.2", Listed below are the errors: [10:58:34] Finished 'build.html_css&apos ...

"Encountered an issue with Next-Auth session returning as undefined in getServerSideProps using NextJS version 13.2

When inspecting the code below, session is found to be undefined upon logging from the client side after being transferred from getServerSideProps. import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[. ...

I am looking for an Angular Observable that only returns a single value without any initial value

Is there a way to create an Observable-like object that calls a webservice only once and shares the result with all subscribers, whether they subscribe before or after the call? Using a Subject would provide the result to subscribers who subscribed before ...

The issue of Next.js 13.4 fetching failing to work properly in a production environment

In development mode, everything runs smoothly. However, when I switch to production and create a new row in Prisma, the API only returns old rows that were present before running npm build. What could be causing this issue, and how can it be resolved? Fro ...

Sources of the TypeScript library in WebStorm

I'm brand new to TypeScript. I decided to use WebStorm because I'm familiar with JetBrains tools. In other programming languages, I'm used to having a workflow that includes some kind of dependency management system like Maven, which allows ...

Error in React due to custom pagination indexing issue

When developing a custom Pagination component in React, I encountered an issue where the indexing restarts from "0" every time the page is changed using the next or previous button. What I want is for the index to start from the last position when clicking ...

The never-ending cycle of an Angular dropdown linked to a function being repeatedly invoked

I am currently working with a PrimeNg dropdown that is fetching its options through a function call. However, I have noticed that this function is being called an excessive number of times. Could this potentially impact the performance or any other aspect? ...

Pause and be patient while in the function that delivers an observable

I have a function that loads user details and returns an observable. This function is called from multiple places, but I want to prevent redundant calls by waiting until the result is loaded after the first call. Can anyone suggest how this can be accompli ...

TypeScript: a sequence of symbols representing a particular <type>

Perhaps I'm going crazy. I have a roster of potential nucleotides and a corresponding type: const DNA = ['G', 'C', 'T', 'A'] as const; type DNA = typeof DNA[number]; So, a DNA strand could be a sequence of an ...

Is there a memory leak causing Node.js memory growth in the (system)?

I have come across a peculiar memory leak in our live environment, where the heap continues to grow due to (system) objects. Heap snapshot Here is a memory dump showing a spike in memory usage up to 800MB: It seems that this excess memory is held within ...

Unusual class title following npm packaging

Currently, I am working on developing a Vue 3 library with TypeScript. We are using Rollup for bundling the library. Everything works as expected within the library itself. However, after packing and installing it in another application, we noticed that th ...

Next.js - useEffect is failing to run at all

Struggling with integrating socket.io into my Next.js app, I decided to simplify my code and gradually add pieces back in. However, this only made things more confusing. The socket is kept in a context provider directly under the body tag in the root layo ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

The error encountered during parsing the module for Next.js, Webpack, and TypeScript files (.ts, .tsx) was due to an unexpected token

Here is the content of my next.config.mjs file: export default { webpack: (config) => { // Find rules that includes current directory const rulesWithCurrentDir = config.module.rules.filter((rule) => rule.include && rule.include.incl ...

Abort S3 file upload using ASW-SDK

Is there a way to abort an upload without raising an error Upload aborted. when calling upload.abort()? import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage"; cons ...

Exploring the process of dynamically incorporating headers into requests within react-admin

Currently utilizing react-admin with a data provider of simpleRestProvider. I am in need of a solution to dynamically add headers to requests based on user interactions. Is there a way to achieve this? Appreciate any assistance. Thank you! ...

Here's a way to resolve the issue: ReactDOM.render() - TS2345 error: Cannot assign type '() => Element' to type 'ReactElement' in the argument

After tackling React-Router with Typescript, I encountered a typing issue that has me perplexed. Prior to this, I was using an older version of React and React-Router. But now, after updating to the latest builds using yarn, I'm facing this hurdle. ...

Perform the subtraction operation on two boolean values using Typescript

I'm working with an array: main = [{ data: x, numberField: 1; }, { data: y, numberField: 2; }, { data: x, numberField: 3; }, { data: z, numberField: 4; }, { data: ...