Bruno Francisco
Bruno Francisco

Reputation: 4240

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?

Upvotes: 3

Views: 2345

Answers (1)

tony19
tony19

Reputation: 138476

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

Upvotes: 6

Related Questions