#Environment Variables Leaked in SSR on HTML Output

7 messages · Page 1 of 1 (latest)

void cosmos
#

Is it true that private server only env variables can be leaked if added to an astro component which is then rendered on the server to html. And how to prevent this? (I am not talking about client islands, I know it is prevented there)

---
console.log(import.meta.env.DB_PASSWORD); // logs the pw in terminal as expected, runs on server
---

<div>
{import.meta.env.DB_PASSWORD} <!-- leaks the password as clear text, runs on server and converts to html (i would like to get error)-->
</div>
<script>
console.log(import.meta.env.DB_PASSWORD); // logs undefined as expected, runs on client
</script>
teal onyx
#

Yep, pretty sure this would be expected. It's not really possible to completely prevent this, especially since you could, for example, take an env variable, apply it to another object, use that in the jsx. There's not really a way to prevent this to my knowledge. Maybe one step would be to never use env variables in .astro files, and move any database/API logic to .ts files as soms level of separation. It's not perfect, just a small step, but I'm not sure if there's a great deal you can do to prevent this

void cosmos
#

Ok good to know, I'm not missing something. I could get used to it, as I have enough experience. But I'm currently working on educational content, and found it quite hard to explain that they are 4 different types of env variables and for all 4 of them there are other rules and outcomes on server and client side. But the idea of separation to ts files is a good one.

marsh apex
#

that's a very good example that shows that html in .astro runs server side and script runs client side. I would not call that a leak, as in any server you could send the password to the client as well. The rendered html is the bridge between you and the client so it should be verified and written by a trusted source only. Vite has dedicated method to by exposing only _PUBLIC as a help for developpers not to get confused, so respect naming don't call your secrets _PUBLIC 😉
https://docs.astro.build/en/guides/environment-variables/

#

a common usage is simply in the frontmatter section to fetch APIs with secrets, that is the best practice, using env in html section is already questionable, as you can alway refactor logic in another subcomponent frontmatter.

void cosmos
#

That are good points too. Agree totally, I was just wondering about a protection guard for new-comers or people not sure how the separation works.

marsh apex