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

This worked for me. I had originally returned “Hello Json” in string. the tests are sensitive. it has to be “Hello json”.

require(‘dotenv’).config();
let express = require(‘express’);
let app = express();

console.log(process.env.MESSAGE_STYLE);

app.use(“/public”, express.static(__dirname + “/public”));

app.get(‘/’, function(req, res) {
const absolutePath = __dirname + “/views/index.html”;
res.sendFile(absolutePath);
});

app.get(“/json”, function(req, res) {
const messageStyle = process.env.MESSAGE_STYLE;

if (messageStyle === “uppercase”) {
res.json({“message”: “HELLO JSON”});
} else {
res.json({“message”: “Hello json”}); // Note the correct casing: “Hello json”
}
});

module.exports = app;