3

I'm using a library that requires a secret string. I've set my node variable like so:

export JWT_SECRET=e177920e88165bd0090b1c6b544cf7

However, when I try to use it in my app, like so:

const jwt = require('jsonwebtoken');

function userToken(user) {
  return jwt.sign({
    user: user.id,
  }, process.env.JWT_SECRET);
}

it hits an error that says the secret must be a string or buffer. I thought node variables are strings, so not sure what the issue is. Thanks.

1
  • for setting enviroment variable in nodejs try this : process.env['VARIABLE'] = 'value'; as you in this code vlaue should be define as string Commented Jan 15, 2017 at 7:13

4 Answers 4

2

Hmm, this works fine for me. Maybe try adding a console.log(process.env.JWT_SECRET) to check that your env var is being loaded correctly.

As a side note, I would also consider using some kind of environment variable management library such as dotenv. It allows you to store a all of your environment variables in a .env file like:

JWT_SECRET="abc"
OTHER_ENV_VAR="def"

It makes it much easier to keep track of your env vars :)

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

Comments

2

Be sure to use the same terminal you exported the environment variable out of.

Comments

0

Try Setting envoirment variable like this

process.env['JWT_SECRET'] = 'e177920e88165bd0090b1c6b544cf7';

Or like This:

var envs = require('envs');

// If NODE_ENV is not set, 
// then this application will assume it's prod by default.
app.set('environment', envs('NODE_ENV', 'production')); 

// Usage examples:
app.set('ga_account', envs('GA_UA'));
app.set('nr_browser_key', envs('NEW_RELIC_BROWSER_KEY'));
app.set('other', envs('SOME_OTHER_TOKEN));

Comments

0

Wow, so realized that I had a few different windows opened for my terminal. I had to set the variable within the window that I was running application in, in order to get access to process.env.JWT_SECRET.

Comments

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.