Use custom user type in Passport.js with Typescript
Used versions
- Node.js: 19.6.0
- Typescript: 5.1.3
- Express: 4.18.2
- Passport: 0.6.0
Problem
The default user type used for serializing the user (passport.serializeUser(user, done)) is Express.User. This type is defined in the @types/passport/index.d.ts file as:
declare global {
namespace Express {
interface User {}
}
}
This is a problem if you want to use a custom user type (e.g.: a User model from a database).
Solution
First, import the the customer type you want to use in the @types/passport/index.d.ts file:
import { User } from "../../src/models/user.model";
Then, delete or comment the User interface:
declare global {
namespace Express {
// interface User {}
}
}
Finally, add the User type to the serializeUser function:
passport.serializeUser((user: User, done) => {
done(null, user.id);
});