or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-integration.mdconfiguration-management.mdcore-build-system.mddevelopment-server.mdenvironment-system.mdenvironment-variables.mdindex.mdplugin-system.md

environment-variables.mddocs/

0

# Environment Variables

1

2

Environment variable loading and management from .env files with mode-specific support. Provides secure and flexible configuration management for different deployment environments.

3

4

## Capabilities

5

6

### Load Environment Variables

7

8

Load environment variables from .env files with mode-specific support.

9

10

```typescript { .api }

11

/**

12

* Load environment variables from .env files

13

* @param options - Environment loading options

14

* @returns Environment loading result with parsed variables

15

*/

16

function loadEnv(options?: LoadEnvOptions): LoadEnvResult;

17

18

interface LoadEnvOptions {

19

/** Working directory to search for .env files */

20

cwd?: string;

21

/** Environment mode for file selection */

22

mode?: string;

23

/** Variable prefixes to expose to client */

24

prefixes?: string[];

25

/** Process environment variables to merge */

26

processEnv?: Record<string, string>;

27

}

28

29

interface LoadEnvResult {

30

/** Raw parsed variables from .env files */

31

parsed: Record<string, string>;

32

/** Paths of loaded .env files */

33

filePaths: string[];

34

/** Raw public variables before formatting */

35

rawPublicVars: Record<string, string | undefined>;

36

/** Formatted public variables for client use */

37

publicVars: Record<string, string>;

38

/** Cleanup function to restore original environment */

39

cleanup: () => void;

40

}

41

```

42

43

**Usage Examples:**

44

45

```typescript

46

import { loadEnv } from "@rsbuild/core";

47

48

// Load from default location

49

const { parsed, publicVars, filePaths } = loadEnv();

50

console.log("Parsed variables:", parsed);

51

console.log("Client variables:", publicVars);

52

53

// Load with specific mode and prefixes

54

const prodEnv = loadEnv({

55

mode: "production",

56

prefixes: ["RSBUILD_", "PUBLIC_"],

57

});

58

console.log("Production public vars:", prodEnv.publicVars);

59

60

// Load from custom directory with cleanup

61

const { parsed, cleanup } = loadEnv({

62

cwd: "/path/to/project",

63

mode: "staging",

64

});

65

console.log("Staging variables:", parsed);

66

// Restore environment when done

67

cleanup();

68

```

69

70

### Environment File Resolution

71

72

Rsbuild loads environment files in the following order (higher priority first):

73

74

1. `.env.{mode}.local` (e.g., `.env.production.local`)

75

2. `.env.local` (always loaded except in test mode)

76

3. `.env.{mode}` (e.g., `.env.production`)

77

4. `.env`

78

79

**File Examples:**

80

81

```bash

82

# .env (base environment variables)

83

DATABASE_URL=localhost:5432

84

API_VERSION=v1

85

86

# .env.local (local overrides, ignored by git)

87

DATABASE_URL=localhost:3306

88

DEBUG=true

89

90

# .env.production (production-specific)

91

DATABASE_URL=prod-db.example.com:5432

92

API_URL=https://api.example.com

93

94

# .env.production.local (production local overrides)

95

DEBUG=false

96

LOG_LEVEL=error

97

```

98

99

### Environment Variable Processing

100

101

```typescript { .api }

102

interface LoadEnvResult {

103

/**

104

* Merged environment variables from all loaded files

105

* Variables from higher priority files override lower priority ones

106

*/

107

env: Record<string, string>;

108

109

/**

110

* Parsed variables organized by source file

111

* Useful for debugging which file provided which variables

112

*/

113

parsed: Record<string, Record<string, string>>;

114

}

115

```

116

117

**Processing Rules:**

118

119

- Variables are loaded and merged with higher priority files overriding lower priority

120

- Empty values are treated as empty strings, not undefined

121

- Comments (lines starting with `#`) are ignored

122

- Multi-line values are supported using quotes

123

- Variable expansion is supported using `${VARIABLE}` syntax

124

125

### Client-Side Environment Variables

126

127

Environment variables available in client-side code during build:

128

129

```typescript { .api }

130

// Available in client code

131

declare const import.meta.env: {

132

/** Build mode */

133

MODE: 'development' | 'production' | 'none';

134

/** True if MODE is 'development' */

135

DEV: boolean;

136

/** True if MODE is 'production' */

137

PROD: boolean;

138

/** Base URL from server.base config */

139

BASE_URL: string;

140

/** Asset prefix URL */

141

ASSET_PREFIX: string;

142

143

// Custom variables (must be prefixed)

144

[key: string]: any;

145

};

146

```

147

148

**Variable Prefixing:**

149

150

Only environment variables with specific prefixes are exposed to client code:

151

152

- `RSBUILD_` - Rsbuild-specific variables

153

- `PUBLIC_` - Public variables exposed to client

154

- Built-in variables (MODE, DEV, PROD, etc.)

155

156

```bash

157

# .env

158

RSBUILD_API_URL=https://api.example.com # Available in client

159

PUBLIC_VERSION=1.0.0 # Available in client

160

PRIVATE_KEY=secret123 # Server-only, not exposed

161

```

162

163

### Integration with Configuration

164

165

Environment variables can be used in Rsbuild configuration:

166

167

```typescript

168

import { defineConfig, loadEnv } from "@rsbuild/core";

169

170

const { env } = loadEnv();

171

172

export default defineConfig({

173

source: {

174

define: {

175

// Expose variables to client code

176

'process.env.API_URL': JSON.stringify(env.RSBUILD_API_URL),

177

'process.env.VERSION': JSON.stringify(env.PUBLIC_VERSION),

178

},

179

},

180

181

server: {

182

port: parseInt(env.PORT || "3000"),

183

proxy: env.PROXY_URL ? {

184

"/api": env.PROXY_URL,

185

} : undefined,

186

},

187

188

output: {

189

assetPrefix: env.ASSET_PREFIX || "/",

190

},

191

});

192

```

193

194

### Mode-Specific Loading

195

196

```typescript

197

// Load development-specific environment

198

const devEnv = loadEnv({ mode: "development" });

199

200

// Load production-specific environment

201

const prodEnv = loadEnv({ mode: "production" });

202

203

// Load staging-specific environment

204

const stagingEnv = loadEnv({ mode: "staging" });

205

```

206

207

### Environment Variable Expansion

208

209

Support for variable expansion within .env files:

210

211

```bash

212

# .env

213

BASE_URL=https://example.com

214

API_URL=${BASE_URL}/api

215

FULL_API_URL=${API_URL}/v1

216

217

# Results in:

218

# BASE_URL=https://example.com

219

# API_URL=https://example.com/api

220

# FULL_API_URL=https://example.com/api/v1

221

```

222

223

### TypeScript Support

224

225

Type-safe environment variable access:

226

227

```typescript

228

// env.d.ts

229

interface ImportMetaEnv {

230

readonly RSBUILD_API_URL: string;

231

readonly PUBLIC_VERSION: string;

232

readonly MODE: 'development' | 'production' | 'none';

233

readonly DEV: boolean;

234

readonly PROD: boolean;

235

}

236

237

interface ImportMeta {

238

readonly env: ImportMetaEnv;

239

}

240

241

// Usage in code

242

const apiUrl = import.meta.env.RSBUILD_API_URL; // Type-safe

243

const isDev = import.meta.env.DEV; // boolean

244

```

245

246

### Security Considerations

247

248

**Server-Side Only Variables:**

249

250

Variables without proper prefixes are only available on the server side:

251

252

```typescript

253

// In server-side code (Node.js)

254

const dbPassword = process.env.DATABASE_PASSWORD; // Available

255

256

// In client-side code (browser)

257

const dbPassword = process.env.DATABASE_PASSWORD; // undefined

258

const apiUrl = import.meta.env.RSBUILD_API_URL; // Available

259

```

260

261

**Best Practices:**

262

263

- Use `.env.local` for local development secrets

264

- Add `.env.local` to `.gitignore`

265

- Use proper prefixes for client-exposed variables

266

- Validate required environment variables at startup

267

- Use separate .env files for different environments

268

269

### Integration with CreateRsbuild

270

271

```typescript { .api }

272

interface CreateRsbuildOptions {

273

/** Environment variable loading configuration */

274

loadEnv?: boolean | LoadEnvOptions;

275

}

276

```

277

278

**Usage:**

279

280

```typescript

281

// Auto-load environment variables

282

const rsbuild = await createRsbuild({

283

loadEnv: true, // Uses default options

284

});

285

286

// Custom environment loading

287

const rsbuild = await createRsbuild({

288

loadEnv: {

289

mode: "production",

290

cwd: "./config",

291

},

292

});

293

294

// Disable automatic environment loading

295

const rsbuild = await createRsbuild({

296

loadEnv: false,

297

});

298

```