Nestjs crashes when throwing error after update to v9

1.2k views Asked by At

I have updated my application from Nest.js v8 to Nest.js v9 and now the application exits every time an error is thrown.

Previously, an HTTPException was simply returned. But now every time the server terminates and I get this error:

`TypeError: Cannot read properties of undefined (reading 'preSerialization')`

System:

Node: 18

The following packages have been updated:

@nestjs/common: 9.2.1
@nestjs/core: 9.2.1
@nestjs/microservices: 9.2.1
@nestjs/platform-express: 9.2.1
@nestjs/platform-fastify: 9.2.1
@nestjs/platform-socket.io: 9.2.1
@nestjs/swagger: 9.2.1
@nestjs/websockets: 9.2.1

The error only occurs when I throw an exception in the middleware, otherwise it works.

@Injectable()
export class AuthMiddleware implements NestMiddleware {
    async use(req: Request, res: Response, next: NextFunction): Promise<NextFunction> {

        if (req.method === 'OPTIONS') {
            next();
        }

        if (!req.headers.authorization) {
            throw new HttpException('No credentials set', HttpStatus.UNAUTHORIZED);
        }

        const token = req.headers.authorization;
        const claims = await authClient.verify(token);

        ....

        next();
    }
}

Has anyone ever had the problem? I think it has something to do with fastify, but haven't found a solution yet.

I have also tried other versions but from v9 it does not work. It does also not work with other node versions.

1

There are 1 answers

0
Srle On BEST ANSWER

Seems like this changes occurs with version greater than 9.1.2, i have reported same issue at https://github.com/nestjs/nest/issues/10781 At this point there is no actual fix for this issue, my temporary solution is to use 9.1.2 (this bug starts with nestjs 9.1.3)

If you really want to use greater than 9.1.2 from where this bug occurs, instead of throwing error from middleware you can use next callback passing an error, and application will not crash.

Instead

if (!req.headers.authorization) {
  throw new HttpException('No credentials set', HttpStatus.UNAUTHORIZED);
}

You can use

if (!req.headers.authorization) {
  return next(new HttpException('No credentials set', HttpStatus.UNAUTHORIZED));
}