Auth0 Home Blog Docs

Auth0 NestJS Sample - I don't understand the middleware code

Trying to get auth0 working with NestJS and it’s great that auth0 has sample code.

The main issue I have with it is that I don’t fully understand the authentication middleware code.

@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {
  resolve(): MiddlewareFunction {
    return (req, res, next) => {
      jwt({
        secret: expressJwtSecret({
          cache: true,
          rateLimit: true,
          jwksRequestsPerMinute: 5,
          jwksUri: 'https://${DOMAIN}/.well-known/jwks.json',
        }),

        audience: 'http://localhost:3000',
        issuer: 'https://${DOMAIN}/',
        algorithm: 'RS256',
      })(req, res, (err) => {
        if (err) {
          const status = err.status || 500;
          const message = err.message || 'Sorry, we were unable to process your request.';
          return res.status(status).send({
            message,
          });
        }
        next();
      });
    };
  }
}

Specifically, I don’t understand why this anonymous function comes immediately after the express-jwt middleware call, without a semi-colon separating it from the express-jwt call.

(req, res, (err) => {
            if (err) {
              const status = err.status || 500;
              const message = err.message || 'Sorry, we were unable to process your request.';
              return res.status(status).send({
                message,
              });
            }
            next();
          });

Anyways, the TS compiler doesn’t like it and I don’t understand it enough to fix it.

I’m trying to use this with the latest NestJS version & TS v3.4.x, and I’m having more trouble because NestJS middleware has been refactored.

Hey there!

Sorry for such huge delay in response! We’re doing our best in providing you with best developer support experience out there, but sometimes our bandwidth is not enough comparing to the number of incoming questions.

Wanted to reach out to know if you still require further assistance?

That tutorial/sample code is a bit outdated. I was facing the same problem as you and ended up making my own template repository. You can find the code here.

Thanks a lot for providing the feedback and sharing it with the rest of community! I’ll make another post with that in our Show YourAuth0 corner here in the forum! Really appreciate that!