Environment variables

Tell us what’s happening:

Environment variable comparison with string not working

Your project link(s)

solution: https://replit.com/@aftab76ahmad76/boilerplate-express-1

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36

Challenge: Use the .env File

Link to the challenge:

The link you’ve posted just gives me a blank screen then redirects back to the replit homepage, not sure if it’s correct or there’s some other problem meaning I can’t connect?

Anyway. Have you followed the instructions here?

Note: If you are using Replit, you cannot create a .env file. Instead, use the built-in SECRETS tab to add the variable.

That is my routte handler

app.get("/json", (req, res) => {

  if (JSON.stringify(process.env.MESSAGE_STYLE.trim()) == JSON.stringify('uppercase')) {
    res.json({ message: "HELLO JSON" })
  }
  else {
    res.json({ message: "Hello json" })
  }

})

When I console process.env.MESSAGE_STYLE it says uppercase but not returning false in comparison even though I have used JSON.stringify & trim method…

And yes I have correctly setup my env-variavles in replit I am sure about them

JSON.stringify() is for stuff that is not already a string. Normally you use it with objects ([] or {}) because servers handle only certain types of formats (not js). [see example at the bottom][1]

process.env.MESSAGE_STYLE is already a string as you can check using typeof.

process.env.VAR.trim() == 'uppercase'

is enough imho.

[1]:

// Example POST method implementation:
async function postData(url = '', data = {}) {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

But I tried its not working

Did you fix it? @aa0140527

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.