Environment variables
Change configuration and API keys without uploading your site again.
Environment variables hold values your code uses, such as an API address. Add them in your site’s settings, then use their names in JavaScript. You can update the values later without rebuilding or uploading your files again.
Add a variable
Choose a name using uppercase letters, digits and underscores, and enter its value. For example, add a public variable named API_BASE with your API’s address. Your code can then use it like this:
<script type="module">
// API_BASE is defined in this site's settings.
const res = await fetch(API_BASE + '/products')
console.log(await res.json())
</script>Sites with environment variables get a small script at the top of their HTML to make the variables available. Sites without variables do not get this script.
Public or secret
| Kind | In the browser | Use it for |
|---|---|---|
| Public | The real value | An API base URL, an OAuth client id, a publishable key |
| Secret | A placeholder, never the value | Anything you would not paste into a public repository |
Using a secret
Add the API’s host to the secret’s allowed list, then use the variable in your request. Lovelycode replaces the placeholder with the real value when sending the request to that host. The value stays out of the browser.
// PAYMENTS_KEY is a secret. api.example.com is on the allowed list.
await fetch('https://api.example.com/charge', {
method: 'POST',
headers: { Authorization: 'Bearer ' + PAYMENTS_KEY },
body: JSON.stringify({ amount: 500 })
})You choose which hosts each secret may be sent to. A secret is never sent anywhere else, and one with no allowed host cannot be used at all. If an API receives the literal text {{PAYMENTS_KEY}}, its host is missing from the list.
Limits
| Limit | Value |
|---|---|
| Variables per site | 50 |
| Value length | 2 KB |
| Allowed hosts per site | 20 |