Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node environment variable not being read as string in app

Tags:

node.js

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.

like image 404
hidace Avatar asked Mar 21 '26 03:03

hidace


2 Answers

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 :)

like image 70
leesio Avatar answered Mar 23 '26 17:03

leesio


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

like image 37
SunDontShine Avatar answered Mar 23 '26 17:03

SunDontShine