0

This should be an easy one yet I cant figure it out at all. I am using firebase to try to verify a token form client side

const isAuthenticated = async (req: Request, res: Response, next: NextFunction) => {
    try {
        let token: string;
        if (req.headers.token !== undefined) {
            token = req.headers.token || '';
            const result = await auth.verifyIdToken(token)
        }
        return next()
    } catch (error) {
        res.status(401).json({
            error:'Invalid token'
        })
    }
}

The error type 'string | string[]' is not assignable to type 'string' in the given on

 token = req.headers.token || '';

The verifyToken is meant to take a string as a parameter and obviously the req.headers.token isn't defined yet. What am i doing wrong?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Udendu Abasili
  • 1,163
  • 2
  • 13
  • 29
  • Are you sure this error corresponds to the `token...` line? Did you try restarting `ts-node`? – MaartenDev Jul 12 '21 at 17:55
  • if token is of type string, and `req.headers.token` can be either a string or a string array, then the error makes sense. `req.headers.token` should be defined by `Request` – Kevin B Jul 12 '21 at 17:56
  • 1
    Seems like the `http` typing of the header resolves to `string | string[] | undefined`, docs: https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules__types_node_http_d_._http_.incominghttpheaders.html – MaartenDev Jul 12 '21 at 17:59
  • 1
    You could try casting it using `token = req.headers.token as string || '';` – MaartenDev Jul 12 '21 at 18:00
  • 3
    ```token = String(Array.isArray(req.headers.token) ? req.headers.token[0] : ( req.headers.token || ''))``` – hanshenrik Jul 12 '21 at 18:09

1 Answers1

0

you can cast the req.headers.token to a string doing this:

token = `${req.headers.token}` || '';

but if it indeed receives a string with more than 1 member the generated string will be a string separated by commas (string, string, string)

would double check the implementation sending an array in the token header