Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enviroment variables in Svelte @ index.html

I would like to use a environmental variable in svelte-kit project but unfornutaely I'm not being able to.

I have tried to:

app.html

<meta name="TESTING" value="%VITE_GOOGLE_TAG%">
<meta name="TESTING" value="<% VITE_GOOGLE_TAG %>">
<meta name="TESTING" value="<% process.env.VITE_GOOGLE_TAG %>">

In my .env I have the variable defined:

VITE_GOOGLE_TAG=xxxxx

But the substitution doesn't happen when I re-start my server.

I'm looking to have a different Google tag manager id for each enviroment. Something like

staging -> xxxxx
production -> yyyyy

How can I access enviromental variables in svelte-kit in my app.html?

like image 815
null Avatar asked Nov 18 '25 13:11

null


1 Answers

The docs describe adding <meta> tags to <head> by using <svelte:head>. If you want that <meta> tag to be present on all pages, that's probably best added to a common layout file (e.g., src/routes/__layout.svelte).

You can access environment variables via import.meta.env.VARNAME. And you can bind that to <meta>.value with Svelte's attribute binding syntax (i.e., the expression surrounded by curly brackets).

<!-- src/routes/__layout.svelte -->
<svelte:head>
  <meta name="TESTING" value={import.meta.env.VITE_GOOGLE_TAG}>
</svelte:head>

demo

like image 151
tony19 Avatar answered Nov 21 '25 10:11

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!