How can I add custom type to NextApiRequest in Next.js? – Next.js

by
Ali Hasan
django-authentication middleware next.js react-typescript

Quick Fix: Use a CustomNextApiHandler, which is a type that extends NextApiHandler and includes your custom userId property. Then, use CustomNextApiHandler as the type for your addCommentHandler and pass it as an argument to the authMiddleware.

The Problem:

In Next.js, I have a middleware that checks for a valid JWT token in requests to APIs. I’m using TypeScript, but encountering a type error. I defined a custom interface that extends NextApiRequest with a userId property, but when I try to use it as the type for req in the middleware function, it doesn’t work. The code works, but I want to fix the type error. An example of how I use the middleware is also provided.

The Solutions:

Solution 1: Using Custom Interface

Next.js uses a custom type for its NextApiRequest interface, so extending it directly can cause type errors. Here’s a solution:

  1. Create a custom interface CustomNextApiRequest that extends NextApiRequest and includes the additional userId property.
  2. Use the CustomNextApiRequest type in your middleware function as the type for the req parameter.
  3. Update the middleware function to assign the userId property to the req object after validating the JWT token.

Q&A

How to use the custom interface in our authMiddleware?

Update the authMiddleware function to take a generic CustomNextApiHandler function parameter: const authMiddleware = (handler: CustomNextApiHandler) = ...

Video Explanation:

The following video, titled "How to Build a REST API with Next.js 13 - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Web Dev Roadmap for Beginners (Free!): https://bit.ly/DaveGrayWebDevRoadmap Learn how to Build a REST API with Next.js 13.