Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat:(env type safe) - add zod validation & declare type #661

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
dist
node_modules
.vscode
.env
12 changes: 11 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"prettier": "^3.2.4",
"rimraf": "^5.0.5",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.3.3"
"typescript": "^5.3.3",
"zod": "^3.22.4"
}
}
4 changes: 3 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const FASTIFY_PORT = Number(process.env.FASTIFY_PORT) || 3006;

app.listen({ port: FASTIFY_PORT });

console.log(`🚀 Fastify server running on port http://localhost:${FASTIFY_PORT}`);
console.log(
`🚀 Fastify server running on port http://localhost:${FASTIFY_PORT}`
);
console.log(`Route index: /`);
console.log(`Route user: /api/v1/user`);
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"node_modules"
],
"include": [
"./src/**/*.ts"
"./src/**/*.ts",
"type.env.ts"
]
}
22 changes: 22 additions & 0 deletions type.env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
*
* Simple configuration that enables type-safe reading of environment variables
* & provides auto-completion support in VSCode.
* Matt Pocock did a video explaining how you can implement this approach:
* see https://www.youtube.com/watch?v=q1im-hMlKhM
*/

import z from "zod";

const envVariables = z.object({
FASTIFY_PORT: z.string(),
DATABASE_URL: z.string(),
});

envVariables.parse(process.env);

declare global {
namespace NodeJS {
interface ProcessEnv extends z.infer<typeof envVariables> {}
}
}