Environment variables
The file src/settings.ts is the central place to contain all configuration variables. However, some variables are different by environment (e.g: development, staging, acceptance, production). They are called environment variables.
To avoid inserting unexpected environment variables in the final bundle, the name of the variables must be prefixed like this:
Application type | Prefix | Example |
---|---|---|
Vite App | VITE_ | VITE_API_URL=https://api.oneki.net |
Next.js APP | NEXT_ | NEXT_API_URL=https://api.oneki.net |
The environment variables can be defined in one of these files:
My-App
│ ├─ src
│ │ ├─ settings.ts
│ │ └─ ...
│
├─ .env.development
├─ .env.development.local
├─ .env.production
├─ .env.production.local
├─ package.json
└─ ...
These files should only contain environment variables.
The entire configuration should be stored in src/settings.ts and environment variables must be referenced using import.meta.env.<env_variable>
(Vite) or process.env.<env_variable>
(Next.js)
Filename | Description |
---|---|
.env.development | Environment variables specific to the development environment. The development environment is started with yarn dev or next |
.env.development.local | same as .env.development but this file should not be committed on GIT. Therefore this file can contain more sensitive data Note: Since a Vite app is executed exclusively on the browser side, it should not contain sensitive data like passwords |
.env.production | Environment variables specific to a production environment. A production environment is any environment built with yarn build. This file is generally not committed on GIT but created by a CI during the construction of the application (the file is therefore different between staging and production) |
.env.production.local | same as .env.production but this file should not be committed on GIT. Therefore this file can contain more sensitive data Note: Since a Vite app is executed exclusively on the browser side, it should not contain sensitive data like passwords |
Example
- Vite App
- Nextjs App
Content of .env.development
VITE_API_URL=https://dev.oneki.net/api
Content of src/settings.ts
export default {
baseUrl: import.meta.env.VITE_API_URL,
notification: {
// variables below common to all environments
default: {
ttl: 1000,
max: 5,
},
},
};
Content of .env.development
NEXT_API_URL=https://dev.oneki.net/api
Content of src/settings.ts
export default {
baseUrl: process.env.NEXT_API_URL,
notification: {
// variables below common to all environments
default: {
ttl: 1000,
max: 5,
},
},
};