環境變數(如 API 金鑰和資料庫憑證)可以新增到 .env
檔案中,它們將可供你的應用程式使用。
你也可以使用
.env.local
或.env.[mode]
檔案 — 請參閱 Vite 文件 以取得更多資訊。請確保將任何包含敏感資訊的檔案新增到你的.gitignore
檔案中!
process.env
中的環境變數也可透過$env/static/private
使用。
在這個練習中,我們希望允許使用者在知道正確的密語(使用環境變數)的情況下進入網站。
首先,在 .env
中,新增一個新的環境變數
PASSPHRASE="open sesame"
開啟 src/routes/+page.server.js
。從 $env/static/private
導入 PASSPHRASE
,並在 表單動作 中使用它
src/routes/+page.server
import { redirect, fail } from '@sveltejs/kit';
import { PASSPHRASE } from '$env/static/private';
export function load({ cookies }) {
if (cookies.get('allowed')) {
redirect(307, '/welcome');
}
}
export const actions = {
default: async ({ request, cookies }) => {
const data = await request.formData();
if (data.get('passphrase') === PASSPHRASE) {
cookies.set('allowed', 'true', {
path: '/'
});
redirect(303, '/welcome');
}
return fail(403, {
incorrect: true
});
}
};
現在,任何知道正確密語的人都可以存取該網站。
保護機密
重要的是,敏感資料不會意外地被傳送到瀏覽器,因為那裡很容易被駭客和惡棍竊取。
SvelteKit 使防止這種情況發生變得很容易。請注意,如果我們嘗試將 PASSPHRASE
導入到 src/routes/+page.svelte
會發生什麼事
src/routes/+page
<script>
import { PASSPHRASE } from '$env/static/private';
let { form } = $props();
</script>
會彈出一個錯誤覆蓋,告訴我們 $env/static/private
無法匯入到客戶端程式碼中。它只能匯入到伺服器模組中
+page.server.js
+layout.server.js
+server.js
- 任何以
.server.js
結尾的模組 src/lib/server
中的任何模組
反過來說,這些模組只能被其他伺服器模組匯入。
靜態 vs 動態
$env/static/private
中的 static
表示這些值在建置時已知,並且可以靜態替換。這可以實現有用的最佳化
import { FEATURE_FLAG_X } from '$env/static/private';
if (FEATURE_FLAG_X === 'enabled') {
// code in here will be removed from the build output
// if FEATURE_FLAG_X is not enabled
}
在某些情況下,你可能需要引用動態的環境變數 — 換句話說,在我們執行應用程式之前都不知道。我們將在下一個練習中介紹這種情況。
上一頁 下一頁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
let { form } = $props();
</script>
<form method="POST">
<label>
enter the passphrase
<input name="passphrase" autocomplete="off" />
</label>
</form>
{#if form?.incorrect}
<p class="error">wrong passphrase!</p>
{/if}
<style>
.error {
color: red;
}
</style>