I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error.
Below is my code snippet:
import { verifyJwtToken } from "../utils/verifyJwtToken.js";
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
import cookie from "cookie"
const authMiddleware = (handler: NextApiHandler) => async (req: NextApiRequest, res: NextApiResponse) => {
try {
const cookies = cookie.parse(req.headers.cookie || '')
const token = cookies.token
const verifiedToken = await verifyJwtToken(token)
if (!verifiedToken) {
throw new Error('You have no access to do it.')
}
const userId = Number(verifiedToken.id)
// Call the API route handler with the updated request object
return handler({ ...req, userId }, res)
} catch (err) {
console.error(err)
res.status(401).json({ message: 'You have no access to do it.' })
}
}
export default authMiddleware;
The type error I encountered is as follows:
Argument of type '{ userId: number; query: Partial<{ [key: string]: string | string[]; }>; cookies: Partial<{ [key: string]: string; }>; body: any; env: Env; preview?: boolean | undefined; ... 35 more ...; eventNames(): (string | symbol)[]; }' is not assignable to parameter of type 'NextApiRequest'.
Object literal may only specify known properties, and 'userId' does not exist in type 'NextApiRequest'.ts(2345)
To resolve this issue, I created a custom interface that extends NextApiRequest
and includes the userId
property. Here is an example:
import { NextApiRequest } from 'next'
interface CustomNextApiRequest extends NextApiRequest {
userId: number
}
export default CustomNextApiRequest;
Subsequently, I attempted to utilize this custom interface as the type for the req
parameter in the middleware function, like so:
import CustomNextApiRequest from './CustomNextApiRequest';
const authMiddleware = (handler: NextApiHandler) => async (req: CustomNextApiRequest, res: NextApiResponse) => {
// ...
}
However, this approach did not work. It's important to note that the code is functional, but I am aiming to rectify the type error.
Additionally, here is how I applied the authMiddleware
:
async function addCommentHandler(req: NextApiRequest, res: NextApiResponse) {
// Implementation logic goes here...
}
export default authMiddleware(addCommentHandler);