0

This is TypeScript code that I wrote a couple of years ago:

import { expressjwt } from "express-jwt";
import { Request } from 'express';

class Authentication {


    static loginRequired() {

        expressjwt({
            secret: process.env.SECRET,
            credentialsRequired: true,
            getToken: function fromHeaderOrQuerystring(req: Request) {
                if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
                    return req.headers.authorization.split(' ')[1];
                } else if (req.query && req.query.token) {
                    return req.query.token;
                }
                return null;
            }
        });
    }
}

export { Authentication as auth };

I am getting an error at the getToken property:

Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>) => string | ParsedQs | (string | ParsedQs)[]' is not assignable to type 'TokenGetter'.
  Type 'string | ParsedQs | (string | ParsedQs)[]' is not assignable to type 'string | Promise<string>'.
    Type 'ParsedQs' is not assignable to type 'string | Promise<string>'.
      Type 'ParsedQs' is missing the following properties from type 'Promise<string>': then, catch, finally, [Symbol.toStringTag]ts(2322)
index.d.ts(37, 5): The expected type comes from property 'getToken' which is declared here on type 'Params'
(property) getToken?: TokenGetter
Defines how to retrieves the token from the request object

When I wrote this code I was using Node 14.

1
  • Perhaps you simply need return req.query.token as string? Commented Nov 19 at 0:22

2 Answers 2

1

Your code has two problems:

  1. getToken should return a string or undefined (the signature is: TokenGetter = (req: express.Request) => string | Promise<string> | undefined;), and req.query returns ParsedQs, so you need to make sure req.query.token is a string, for example:
return req.query.token as string; // or implement string validation
  1. your options is missing now required algorithms parameter.

Try the full code:

static loginRequired() {

    expressjwt({
        secret: process.env.SECRET,
        credentialsRequired: true,
        getToken: function fromHeaderOrQuerystring(req: Request) {
            if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
                return req.headers.authorization.split(' ')[1];
            } else if (req.query && req.query.token) {
                return req.query.token as string; // or implement string validation
            }
            return null;
        },
        // required
        algorithms: ['HS256'] //supported algorithms: https://github.com/auth0/node-jsonwebtoken#algorithms-supported
    });
}

see: express-jwt API

Sign up to request clarification or add additional context in comments.

Comments

-1

The error happens because newer versions of express-jwt require getToken to return only a string or Promise<string>.

But req.query.token in Express can be string | string[] | ParsedQs | ParsedQs[], so TypeScript won’t accept it.

You just need to narrow the query value to ensure you return only a string:

import { expressjwt } from "express-jwt";
import { Request } from "express";

class Authentication {
  static loginRequired() {
    return expressjwt({
      secret: process.env.SECRET as string,
      credentialsRequired: true,
      getToken: (req: Request) => {
        if (
          req.headers.authorization &&
          req.headers.authorization.startsWith("Bearer ")
        ) {
          return req.headers.authorization.split(" ")[1];
        }

        const token = req.query.token;

        // Only return a string to satisfy TokenGetter
        if (typeof token === "string") {
          return token;
        }

        return null;
      },
    });
  }
}

export { Authentication as auth };

Why this fixes it:
By checking typeof token === "string", you guarantee the function returns a valid type (string | null).
The older version you wrote years ago worked because express-jwt had looser typings; the newer typings are stricter.

1 Comment

Please note that Generative AI (e.g., ChatGPT) is banned and read Help Center: AI policy. It is not permitted to use AI tools to generate or reword content that you post on Stack Overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.