Wie erweitert man das Request-Objekt in Express mit TypeScript
Hallo zusammen! Ich schreibe ein Backend mit Express und TypeScript und bin auf ein Problem mit der Typisierung des Request-Objekts gestoßen.
Ich habe eine Middleware, die nach der Authentifizierung Benutzerdaten zur Anfrage hinzufügt. Ich mache das ungefähr so:
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
interface UserPayload {
id: string;
email: string;
role: 'admin' | 'user';
}
export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'Kein Token' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!) as UserPayload;
req.user = decoded; // TypeScript-Fehler: Property