How to set environment variables for deploy-preview context in svelte-kit app?

Hi,

I am trying to set different runtime environment variables for production and deploy-preview contexts.
The idea is that the deploy-previews would work as a test environment.

This is for a svelte-kit app.

To get an idea:
I have an API endpoint that sends messages to Telegram. I would like to use a different bot token and chat id in preview-deploy and production

I have tried to follow what was suggested in those posts without success:

I even tried to pass the values in the netlify.toml file for each environment variables but it didn’t work.

My guess is that those values are only available during build time. So is there a way to set environment variables available in runtime for different contexts?

And my current netlify.toml looks like that:

[build]
  command = "npm run build"
  publish = "build"

[[plugins]]
  package = "@netlify/plugin-lighthouse"
  # optional, deploy the lighthouse report to a path under your site
  [plugins.inputs]
    output_path = "reports/lighthouse.html"

[context.deploy-preview]
  command = "sed -i \"s|PREVIEW_TELEGRAM_TOKEN|${PREVIEW_TELEGRAM_TOKEN}|g\" netlify.toml && sed -i \"s|PREVIEW_TELEGRAM_CHAT_ID|${PREVIEW_TELEGRAM_CHAT_ID}|g\" netlify.toml && yarn build"
  [context.deploy-preview.environment]
    TELEGRAM_TOKEN = "PREVIEW_TELEGRAM_TOKEN"
    TELEGRAM_CHAT_ID = "PREVIEW_TELEGRAM_CHAT_ID"

[context.production]
  command = "sed -i \"s|PROD_TELEGRAM_TOKEN|${PROD_TELEGRAM_TOKEN}|g\" netlify.toml && sed -i \"s|PROD_TELEGRAM_CHAT_ID|${PROD_TELEGRAM_CHAT_ID}|g\" netlify.toml && yarn build"
  [context.production.environment]
    TELEGRAM_TOKEN = "PROD_TELEGRAM_TOKEN"
    TELEGRAM_CHAT_ID = "PROD_TELEGRAM_CHAT_ID"

Hey there, @chengjo0 :wave:

Sorry to hear you are encountering difficulties! I appreciate that you have shared your debugging steps already. Can you also share your site URL and repo with us? This will help us look into this situation for you further.

Thanks!