环境变量

Qwik 应用程序可以通过两种主要方式读取环境变量:构建时变量服务器端变量

process.env 是一个仅适用于 Node.js 的 API,应该尽量避免使用。

构建时变量

构建时变量由 Vite 提供支持。它们在 .env 文件中定义,并且可以在浏览器和服务器端代码中使用

重要!请勿使用 import.meta.env.PUBLIC_* 存储任何敏感信息,如 API 密钥、密码等。仅限公共数据

请注意,构建时变量应被视为公共变量,因为它们将被硬编码在浏览器构建中,任何人都可以轻松读取。

构建时变量默认以 PUBLIC_ 为前缀,并且可以通过 import.meta.env.PUBLIC_* 访问。

.env
PUBLIC_API_URL=https://api.example.com
src/routes/index.tsx
import { component$ } from '@builder.io/qwik';
 
export default component$(() => {
  // `import.meta.env.PUBLIC_*` 变量可以在任何地方读取,包括浏览器中
  return <div>PUBLIC_API_URL: {import.meta.env.PUBLIC_API_URL}</div>
})

import.meta.env.PUBLIC_* 变量可以在任何地方读取,但请不要在其中放置任何敏感信息,因为它们将对客户端可见。

服务器端变量

服务器端变量本质上是仅在服务器端代码中可用的运行时变量。

它们在构建时未知,并且在浏览器中不可用,因此可以视为私有变量。

服务器端变量只能在仅在服务器端暴露 RequestEvent 对象的服务器端 API 中访问,例如 routeLoader$()routeAction$()server$() 和端点处理程序,如 onGetonPostonRequest 等。

src/routes/index.tsx
import {
  routeLoader$,
  routeAction$,
  server$,
  type RequestEvent,
} from '@builder.io/qwik-city';
 
export const onGet = (requestEvent: RequestEvent) => {
  console.log(requestEvent.env.get('DB_PRIVATE_KEY'));
};
 
export const onPost = (requestEvent: RequestEvent) => {
  console.log(requestEvent.env.get('DB_PRIVATE_KEY'));
};
 
export const useAction = routeAction$(async (_, requestEvent) => {
  console.log(requestEvent.env.get('DB_PRIVATE_KEY'));
});
 
export const useLoader = routeLoader$(async (requestEvent) => {
  console.log(requestEvent.env.get('DB_PRIVATE_KEY'));
});
 
export const serverFunction = server$(function () {
  // `this` 是 `RequestEvent` 对象
  console.log(this.env.get('DB_PRIVATE_KEY'));
});

定义服务器端变量

在开发过程中,可以在 .env.local 文件中定义服务器端变量,该文件默认被 Git 忽略,因此可以安全地将敏感信息放入其中。

.env.local
DB_PRIVATE_KEY=123456789

确保永远不要将 .env.local 文件提交到 Git。

在生产环境中,设置服务器端变量非常依赖于具体的平台。大多数平台允许您从其仪表板或 CLI 设置环境变量。有关更多信息,请参阅您所使用的平台(cloudflare、vercel、netlify)的文档。

Contributors

Thanks to all the contributors who have helped make this documentation better!

  • manucorporat
  • the-r3aper7