I am trying to create a custom wrapper function for my NextJs API routes that will verify a JWT in the request, validate it, and then execute the original API handler.
Here is how I have defined my wrapper function:
interface ApiError {
message: string,
}
export async function withJwt<T>(
handler: ((req: NextApiRequest, res: NextApiResponse<T>, user?: User)=>void|Promise<void>))
: Promise<(req: NextApiRequest, res: NextApiResponse<T | ApiError>)=>Promise<void>> {
return async (req: NextApiRequest, res: NextApiResponse<T | ApiError>) => {
const authHeader = req.headers.authorization;
if(!authHeader || !authHeader.startsWith(JWT_PREFIX)){
return res.status(401).json({
message: `Provide the header 'Authorization: ${JWT_PREFIX}<token>'`,
});
}
let user: User;
try {
user = await verify(authHeader.substring(JWT_PREFIX.length));
} catch(err) {
return res.status(401).json({message: (err as any).message as string});
}
try {
return handler(req, res, user);
} catch(err){
return res.status(500).json({message: (err as any).message});
}
};
}
This is how my API route is structured:
// page/api/hello.ts
type Data = {
name: string
}
const wrapped = withJwt((
req: NextApiRequest,
res: NextApiResponse<Data>
) => {
res.status(200).json({ name: 'John Doe' })
});
export default wrapped;
However, when I visit /api/hello
, I encounter the following error message:
Server Error
TypeError: resolver is not a function
Uncaught at Object.apiResolver (file:///root/projects/taskmanager-next/node_modules/next/dist/server/api-utils.js:101:15) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async DevServer.runApi (file:///root/projects/taskmanager-next/node_modules/next/dist/server/next-server.js:320:9) at async Object.fn (file:///root/projects/taskmanager-next/node_modules/next/dist/server/base-server.js:486:37) at async Router.execute (file:///root/projects/taskmanager-next/node_modules/next/dist/server/router.js:228:32) at async DevServer.run (file:///root/projects/taskmanager-next/node_modules/next/dist/server/base-server.js:598:29) at async DevServer.run (file:///root/projects/taskmanager-next/node_modules/next/dist/server/dev/next-dev-server.js:444:20) at async DevServer.handleRequest (file:///root/projects/taskmanager-next/node_modules/next/dist/server/base-server.js:305:20)
What could be causing this issue?