Environment variables
Env variables are a common way to configure applications, and it’s important to have them type checked. The Schema provider can be used to achieve this.
By using the env-schema
package, you can achieve this easily.
sh
npm i env-schema
1
ts
export interface Environment {
/**
* @minimum 1000
* @maximum 65535
*/
PORT: number;
/** @default 'development' */
NODE_ENV: 'development' | 'production';
/** @format email */
EMAIL: string;
}
1
2
3
4
5
6
2
3
4
5
6
Which can be later used in a separated file:
ts
import { KitaSchemas } from '@kitajs/runtime';
import envSchema from 'env-schema';
import type { Environment } from './providers/schema';
export const Env = envSchema<Environment>({
schema: KitaSchemas.Environment,
dotenv: true
});
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Simply doing the above, you have type checked environment variables.
ts
import Kita from '@kitajs/runtime';
import fastify from 'fastify';
import { Env } from './env';
const app = fastify();
app.register(Kita);
app
.listen({
// type checking works here
port: Env.PORT
})
.then(console.log);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14