Not able to overwrite next-server type definitions for Express
See original GitHub issueBug report
Describe the bug
I’m using Express as a custom server and my project is setup with Typescript with Next.js v8.1.1-canary.29.
When I want to use req or res express object in getInitialProps of pages/_document.tsx Typescript complain when I access properties that are only defined in express server and not http server (eg: req.ip)
As I usually do with other libraries I tried to override the next-server module type and set req and res to their corresponding express types. https://github.com/Neophy7e/next-js-typescript-overide-example/blob/master/types/next-server.d.ts
But after multiple attempt it seems like I can only add new property to the module but I can’t replace existing ones.
Any idea why ?
To Reproduce
I’ve created a sample repo with bare minimum to showcase the issue :
Typescript complain about this line https://github.com/Neophy7e/next-js-typescript-overide-example/blob/master/pages/_document.tsx#L15
Even when trying to override the DocumentContext type here req type stays IncomingMessage
I haven’t set express as a custom server but it assumes it.
Expected behavior
Next.JS types can be overwritten for example when using a custom server.
System information
- OS: macOS
- Version of Next.js: v8.1.1-canary.29
Issue Analytics
- State:
- Created 4 years ago
- Comments:12 (6 by maintainers)

Top Related StackOverflow Question
Hi @Neophy7e, thank you for filling this issue 💯 , the current
reqandreswere made thinking only in thehttpmodule, and that’s firing back actually, the only way you can actually extend it is by extendingIncomingMessage, but it’s aclassand not aninterfaceso it’s not possible 😢. For the moment the best solution I can think of is switch to useas RequestHere’s an alternative solution that can be implemented in Next.js, what if instead of
we use
And
NextRequestwould just beit should allow declaration merging so you can add custom properties on it like this
or even
For anyone else running into this, I was able to extend the types with:
To allow the same kind of typing in my
expressserver, I have:Which allows me to have
expressmiddleware, like:The net result is that I can have proper type-safety from my express middleware all the way down into my next custom app’s
getInitialPropsmethod.