0

Using typescript and nodejs, and express-jwt for validation of authenticity. When we use the express-jwt together with unless, as can be seen as below, tslint is complaining about the possible undefined value returned after the unless function.

import * as express from "express";
import * as jwt from "express-jwt";
import * as http from "http";

const refConfig = {hash: 'mycompletelysecrethashstring', othersetting: 1 };

app.use("/api", jwt({ secret: refConfig.hash }).unless({ path: ["/api/auth/signin"] }));
app.set("port", 8000);
const server: http.Server = app.listen(app.get("port"), () => {
    console.log("Server is now running on port " + server.address().port);
});

The error message is as below:

[ts] Object is possibly 'undefined'.

Is it possible to get rid of this warning, and if so, what is the correct way of doing so?

The issue is with the below line:

app.use("/api", jwt({ secret: refConfig.hash }).unless({ path: ["/api/auth/signin"] }));

As far as I can tell, TypeScript compiler is complaining that the list of routes might be an empty list at the end of unless. Given that the original list is a superset of "/api/auth/signin" it is not a valid concern, but I can't get rid of the warning.

Thanks in advance.

2 Answers2

2

Unless you're missing it from the example, you need to create the app instance :

const app = express() 
app.use(/*...*/)

Also, from your example, jwt is not a function but an object. Try,

import jwt from 'express-jwt'
johngeorgewright
  • 1,005
  • 1
  • 9
  • 19
  • This is only the part of the application, and everything else is working fine except the warning on the line mentioned in the question. – Ali Rıza Dikici May 31 '17 at 05:31
0

You are using refConfig.hash without determining whether refConfig itself is first defined.

You should instead do something like:

if (refConfig) {
   app.use("/api", jwt({ secret: refConfig.hash }).unless({ path: ["/api/auth/signin"] }));
}

A more complete check would be to validate your configuration beforehand and deal with the case where it is incomplete (e.g. exit early with an error for the user).

elithrar
  • 23,364
  • 10
  • 85
  • 104