I am new to typescript and experimenting with porting an express app to use typescript. The server uses JWTs for authentication/authorisation and I have a utility function that decodes and verifies a given token. The function is wrapped in a promise so I can use async/await in the middleware that implements it.
import httpError from 'http-errors';
import jwt from 'jsonwebtoken';
const { ACCESS_TOKEN_SECRET } = process.env;
export function verifyAccessToken(token: string): Promise<jwt.JwtPayload | undefined> {
return new Promise((resolve, reject) => {
jwt.verify(token, ACCESS_TOKEN_SECRET as string, (err, payload) => {
if (err) {
return reject(new httpError.Unauthorized());
}
return resolve(payload);
});
});
}
This function works fine, however I have additional information in the JWT. Specifically I have a role
property, thus the payload is of type:
{
sub: string, // ID issued by mongoose
role: string, // My new information that is causing error
iat: number,
exp: number
}
My problem is that the type for JwtPayload from @types/jsonwebtoken does not contain role
hence when the Promise resolves, I get a typescript error when trying to access payload.role
in the authentication middleware.
import { RequestHandler } from 'express';
import httpError from 'http-errors';
import { verifyAccessToken } from '../utils'
export const authenticate: RequestHandler = async (req, res, next) => {
try {
const authHeader = req.headers['authorization'] as string;
if (!authHeader) {
throw new httpError.Unauthorized();
}
const accessToken = authHeader.split(' ')[1];
if (!accessToken) throw new httpError.Unauthorized();
const payload = await verifyAccessToken(accessToken);
// If I try to access payload.role here I get an error that type JwtPayload does not contain 'role'
next();
} catch (err) {
next(err);
}
};
How do I extend the JwtPayload type to add the role property? I have tried to define my own custom type and completely override the type returned from jwt.verify()
but this throws an error that no overload matches this call.
interface MyJwtPayload {
sub: string;
role: string;
iat: number;
exp: number;
}
// ... then in the utility function replace jwt.verify() call with
jwt.verify(token, ACCESS_TOKEN_SECRET as string, (err, payload: MyJwtPayload) => {
Thanks.
You should be able to achieve this via declaration merging.
Somewhere in your code add this:
declare module "jsonwebtoken" {
export interface JwtPayload {
role: string;
}
}
This should extend the interface as you want it.