Corey Stewart
Corey Stewart

Reputation: 197

express-jwt not accessing .env variable

I have dotenv, jsonwebtoken, and express-jwt packages.

When I create a token with jsonwebtoken the env variable is found and works as expected:

...
  const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {
            expiresIn: "7d",
        });
    ...

However, when I use the express-jwt package with this code:

router.get(
    "/current-user",
    expressjwt({
        secret: process.env.JWT_SECRET,
        algorithms: ["HS256"],
    }),
    currentUser
);

I get the following error:

RangeError: express-jwt: `secret` is a required option

I can workaround the error by hard coding the secret string in like so:

...
secret: "mySuperSecret",
...

A hard coded string is what is shown in the official documentation; obviously, this isn't a realistic solution.

I'm using the .env variables successfully in several places (port, database, signing the token).

Why is the .env variable not being picked up by this one package, or in this one option?

Upvotes: 0

Views: 336

Answers (0)

Related Questions