I couldn't find a clear way of passing variables from a middleware to a constructure in Nest.js. I'm validating a JWT inside my AuthMiddleware and I want to make this token accessible to the controllers.
Below is just an extract of my middleware to provide a code sample. I want to make the token accessible inside of my Controllers.
import { Request, Response, NextFunction } from 'express';
// other imports
@Injectable()
export class AuthMiddleware implements NestMiddleware {
async use(req: Request, res: Response, next: NextFunction) {
const authHeader = req.header('authorization');
if (!authHeader) {
throw new HttpException('No auth token', HttpStatus.UNAUTHORIZED);
}
const bearerToken: string[] = authHeader.split(' ');
const token: string = bearerToken[1];
res.locals.token = token;
}
}
I already tried to make the token accessible by changing the res.locals variable but the response object is still empty in my controller.
This is my controller in which I want to access the token of the middleware:
@Controller('did')
export default class DidController {
constructor(private readonly didService: DidService) {}
@Get('verify')
async verifyDid(@Response() res): Promise<string> {
console.log(res)
// {}
return res;
}