Basic Node and Express - Use the .env File

Challenge: Basic Node and Express - Use the .env File
Hi sorry to ask. I am struggling here. Even examples I have seen make no sense of this. It will not be capitalised but I have lost the thread of why MESSAGE_STYLES appears tagged on the back of process.env
Link to the challenge:


let MESSAGE_STYLE = "Hello json";
if (MESSAGE_STYLE ==="Hello json".toUpperCase()){
  MESSAGE_STYLE = "HELLO JSON" ;
  }else{
  MESSAGE_STYLE;
  };
app.get("/json", function(req, res){ 
process.env.MESSAGE_STYLE(__dirname +  MESSAGE_STYLE)
}); 

Your browser information:

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

ā€œprocess.env.MESSAGE_STYLEā€ is a dot notation to refer to the enviroment variable ā€œMESSAGE_STYLEā€ which is a property of the object ā€œprocess.envā€.

ā€œprocess.envā€ holds all the values of environment variables as properties of the object, thus you need to refer to the variable with the dot notation ā€œprocess.env.MESSAGE_STYLEā€.
This reference to the variable is only for reading the value ā€œuppercaseā€ in your script.

If you want to declare the variable and store the value ā€œuppercaseā€, do as follows:
if you are using replit you need to use secret tabs to store this variable.
If running project locally, store it in a ā€œ.envā€ file.
Donā€™t store the variable by declaring let message=ā€œuppercaseā€, it doesnā€™t work for environment variables.

you can view the link provided by the hints here for the answer.

1 Like

i am not able to find the problem can you help me here is my code :
const express = require(ā€˜expressā€™);
const app = express();
const path = require(ā€˜pathā€™);
const mySecret = process.env.MESSAGE_STYLE;

app.get(ā€˜/ā€™, (req, res) => {
res.sendFile(path.join(__dirname, ā€œviewsā€, ā€œindex.htmlā€));
});

app.use(ā€˜/publicā€™, express.static(path.join(__dirname, ā€˜publicā€™)));

app.get(ā€œ/jsonā€, (req, res) => {
if (mySecret === ā€œuppercaseā€) {
res.json({ ā€œmessageā€: ā€œHELLO JSONā€ });
} else {
res.json({ ā€œmessageā€: ā€œhello jsonā€ });
}
});

module.exports = app;

@w3nch It would be better if you open a new thread when you have questions.

Anyway, process.env.MESSAGE_STYLE needs to be evaluated inside the route handler for the tests to work.

thanks and i will keep that in my mind from now on :slight_smile:

If anyone is still having problems. It worked for me as follows.

var message= 'Hello json';
app.get("/json", (req, res) => {
  if ( process.env['MESSAGE_STYLE'] === "uppercase") {
      res.json({ "message": message.toUpperCase() });
  }
  else {
    res.json({ "message": messange });
  }
});
1 Like

When working with Replit, itā€™s essential to be cautious about whitespace, especially when adding secrets. An unintended whitespace can lead to unexpected behavior or results.

For instance, consider these two scenarios:

Scenario 1: Extra space at the end of the value

{
  "MESSAGE_STYLE": "uppercase "
}

Scenario 2: No extra space

{
  "MESSAGE_STYLE": "uppercase"
}

The difference might seem trivial, but when your code relies on these exact values, such minor discrepancies can lead to significant issues.

Hereā€™s a solution Iā€™ve implemented which not only sends back the message but also the style itā€™s using. This way, you can instantly check the messageStyle returned in the response and verify if the environment variable has any unintended whitespace:

app.get("/json", (req, res) => {
  const message = "Hello json";
  const { MESSAGE_STYLE } = process.env;

  const responseObject = {
    message: MESSAGE_STYLE === "uppercase" ? message.toUpperCase() : message,
    messageStyle: MESSAGE_STYLE
  };

  res.json(responseObject);
});

This approach helps in immediately identifying any discrepancies in the MESSAGE_STYLE value.

Hope this helps! Always double-check for any unintended whitespace when working with secrets or environment variables.

1 Like

If you still have problems this worked for me:

app.get("/json", async (req, res) => {
	try {
		process.env.MESSAGE_STYLE == `uppercase`
			? res.status(200).json({ message: "HELLO JSON" })
			: res.status(200).json({ message: "Hello json" });
		console.log("get /json for dataPakage");
	} catch (error) {
		res.status(404).send({
			statusCode: 400,
			error: error,
		});
	}
});

OK, hereā€™s the code work for me, hope that can help :

app.get("/json", (req, res) => {
  var message = 'Hello json';
  if ( process.env.MESSAGE_STYLE === "uppercase") {
        message = message.toUpperCase();
  }
  res.json({ "message": message });
});

I kind of test most of error to make some summary :

  1. Set the variable ā€œmessageā€ inside the function (outside get error)
  2. Use the console.log( process.env.MESSAGE_STYLE) to see if correct (if you use replit, try this path to set env variable : (1.) ctrl + J (2) select ā€œChange Tabā€ , find ā€œSecretsā€, add ā€œNew Secretā€ (3) set ā€œMESSAGE_STYLEā€ and ā€œuppercaseā€ as key and value
  3. Try to combine all of this chapter code to realize what are we doing here.

My learning code in replit