[typescript] Add the possibility to extend `NextApiRequest` with custom fields
See original GitHub issueFeature request
It’s often the case, when we add a middleware for example, that we need to add extra informations in the req object.
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
req.session.set('user', user)
}
This emit a TS error:
Property 'session' does not exist on type 'NextApiRequest'.
I would like a way to extend the type NextApiRequest with session here for example.
Express tackles this problem with declaration merging: see here.
As a temporary workaround, I created a custom type, but that’s not ideal because it forces me to import this type instead of the “builtin” type next provides.
export type NextApiRequestWithSession = NextApiRequest & {
session: Session
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (6 by maintainers)
Top Results From Across the Web
How to add TypeScript types to request body in Next.js API ...
You can create a new interface that extends NextApiRequest and adds the typings for the two fields. interface ExtendedNextApiRequest extends ...
Read more >How to extend the Express Request object in TypeScript
Let's learn how to extend the Request type in TypeScript to make its instances store custom data you can use at the controller...
Read more >Next.js + TypeScript: Tips and FAQs for Every Stage of Your ...
While next.config.js must be a JavaScript file since it does not get parsed by Babel or TypeScript, it is possible to add some...
Read more >Basic Features: TypeScript - Next.js
Next.js supports TypeScript by default and has built-in types for pages ... Providing your own tsconfig.json with custom compiler options is also supported....
Read more >How to Unit Test Next.js API Routes with TypeScript
js framework because it offered so many of the benefits I listed above, one of the most important being the the ability to...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Nice! Thanks 😃
Looking forward for #12186
This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.