How can I use .env variables in client side code?

This is going to sound noob-ish, but I have recently started both front and back-end coding. I am trying to make a password protected page that checks the password entered against a .env secret. I am aware that you cannot call it on the client side but have to send it through the server side using response.send (As I said I am new so forgive me if this is not the only way). But how would I “catch” that and use that on the client side? Or is that not how it works…

Hi,

You should never use env variables in client side because your secrets will then be visible for everyone visiting your page (show source code or inspect element). No point of using authentication in that case…

You should have an input where the user have to enter the secret and then compare it in back end against your env variables.

happy coding :slight_smile:

1 Like

That’s right, you don’t want to pass your env variables to the client-side, rather pass details from the client-side and check them against env variables server-side. Our passport-js example app does this with support for user login using credentials stored in the .env file. You might find reading the code useful to understand how it works. The main parts are:

The front-end login form: https://glitch.com/edit/#!/passport-js?path=views/auth/local.html:1:0

That form passes data to the /login route defined in https://glitch.com/edit/#!/passport-js?path=auth/local.js:1:0

There’s a function for finding the user: https://glitch.com/edit/#!/passport-js?path=db/users.js:71:14

Which is used to check the relevant password stored in .env: https://glitch.com/edit/#!/passport-js?path=auth/local.js:1:0

2 Likes

Thank you, that was helpful. I looked up post methods and how to handle them and wrote this simple form to test it and a simple php script see if the password entered is sending.

/fun/party.html

<form action="/server.php" method="post">
	<div>
	<label>Password:</label><br>
	<input type="password" name="password"/>
	</div>
	<div>
	<input type="submit" value="Submit"/>
	</div>
</form>

server.php

<html>
<body>

<?php echo $_POST["password"]; 

echo process.env.PASSWORD;
?>

</body>
</html>

But when I tested it out all it comes back with is

OK

Am I doing something wrong? My project is at https://shoeman.glitch.me/ (Dont ask about the name)