Trying to teach myself how to use process.env.SECRET

Hello I am trying to use process.env.MY_PASSWORD in a .js script but it doesn’t seem to so anything. This is my first attempt assigning an env to a js file…

I am trying to make a login page, understand that the site won’t be “secure” with this type of login but am just trying to expand my skills so to speak, and thought this would be a good place to start.

js

  function checkLogin() {
  require("dotenv").config();
  var pword = document.getElememtById("uname");
  var uname = document.getElememtById("pword");
  const password = process.env.MY_PASSWORD;
  const username = process.env.MY_USERNAME;

  if (uname == username && pword == password) {
    window.location(process.env.MY_WEBSITE);
  }
    else alert("Failed")
}

html

  <form class="box" id="loginForm" action="">
        <h1>Login</h1>
        <input type="text" name="uname" id="uname" placeholder="Username" required />
        <input type="password" name="pword" id="pword" placeholder="Password" required />
        <input
          type="submit"
          name="login"
          id="submitbtn"
          value="Login"
          onclick="checkLogin()"
        />
      </form>

End

Thanks for looking I expect im way off here?

Ah! So the process.env.SOME_VARIABLE variables that you define in the .env file are only available on the server (in Node.js). They’re not available in javascript that runs in the browser.

This is because .env variables should be private secrets that you don’t want anyone else seeing, and if you expose them in the browser, anyone could access them (using view-source, for example).

2 Likes

For the future, only keep secret info on the server side.

1 Like