Heisenberg
Heisenberg

Reputation: 5299

How to generate and set `JWT_SECRET` and `JWT_EXPIRATION_TIME` in express

When I run my server,I suffered following errors.

Error: Config validation error: "JWT_SECRET" is required. "JWT_EXPIRATION_TIME" is required

Therefore I must set JWT secret key and so on.

I'd like to know how to set JWT_SECRET.But I couldn't figure out how to generate and set them.

I set.env file,I must configure some of variables in them.

my.env file is like following.

.env

JWT_SECRET=
JWT_EXPIRATION_TIME=

If someone know good way to generate SECRET please let me know.

Thanks

Upvotes: 10

Views: 62067

Answers (4)

NataliaUstinova
NataliaUstinova

Reputation: 181

You can generate a token in the console by running this command:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'));"

then add the generated token to your .env file

Upvotes: 18

Hyardlung
Hyardlung

Reputation: 41

The other users have already answered the question of how to set JWT_SECRET, and I'll add how to generate it. @slebetman gave good advice to generate the string using password generators (they exist both separately and as part of most password managers). For this purpose, I usually use the following command, which I simply enter into the terminal and copy it to the .env file:

openssl rand -base64 172 | tr -d '\ n'

Where 172 is the number of characters in the generated string (choose the one you want).

I hope it will be helpful :)

Upvotes: 4

ksa
ksa

Reputation: 331

As mentioned by @Arya and @JaromandaX, you have to type something after JWT_SECRET something like this JWT_SECRET=yourfavoritecolor and JWT_EXPIRATION_TIME=3600. You can call them in your code with process.env.JWT_SECRET and process.env.JWT_EXPIRATION_TIME.

Check this article on JWT-Right way of implementing JWT

Upvotes: 8

Aryan
Aryan

Reputation: 3638

It's Very simple you just have to add this to your .env file

JWT_SECRET=  any text or number you want to add here to create jwt Token
JWT_EXPIRATION_TIME= you have to specify time limit like you want thattoken expire in 24 hours you have to add  60 * 60 * 24 or  86400 // 24 hours

and there is no other way to generate secrert

Upvotes: 4

Related Questions