Automatic environment variable strong typing #1152
Unanswered
enricoschaaf
asked this question in
Ideas
Replies: 1 comment 1 reply
-
Good suggestion! In addition to that, you need to actually check if the env var exists, and if not, throw a helpful error. Here's what I'm currently using in apps. // config/clientEnv.ts
/* eslint-disable no-process-env */
import * as e from "envsafe"
// ----------------------------------------------
// ENV: Isomorphic, included in client bundle
// - NOTE: You must also add these vars to
// `env` in `blitz.config.js`
// ----------------------------------------------
export const clientEnv = e.envsafe({
isDevelopment: e.bool({ input: (process.env.NODE_ENV === "development") as any }),
isProduction: e.bool({ input: (process.env.NODE_ENV === "production") as any }),
isTest: e.bool({ input: (process.env.NODE_ENV === "test") as any }),
LOG_LEVEL: e.str({ default: "" }),
APP_ORIGIN: e.url({
devDefault: "http://localhost:3000",
input: process.env.VERCEL_URL || process.env.APP_ORIGIN,
}),
// VERCEL_URL: e.str({ default: process.env.VERCEL_URL, devDefault: "" }),
SENTRY_DSN: e.str({ input: process.env.SENTRY_DSN, devDefault: "" }),
STRIPE_KEY: e.str({ input: process.env.STRIPE_KEY }),
TIMEKIT_KEY: e.str({ input: process.env.TIMEKIT_KEY }),
TIMEKIT_PROJECT: e.str({ input: process.env.TIMEKIT_PROJECT }),
}) // config/serverEnv.ts
/* eslint-disable no-process-env */
import * as e from "envsafe"
import { clientEnv } from "./clientEnv"
// ----------------------------------------------
// ENV: Server-side only
// ----------------------------------------------
export const serverEnv = {
...clientEnv,
...e.envsafe({
RAILS_API_URL: e.str({ devDefault: "http://localhost:3000" }),
POSTMARK_TOKEN: e.str({ devDefault: "?" }),
USERLIST_TOKEN: e.str({ devDefault: "?" }),
STRIPE_API_KEY: e.str(),
STRIPE_KEY: e.str(),
TIMEKIT_API_TOKEN: e.str(),
SENTRY_DSN: e.str({ devDefault: "" }),
SENTRY_ORG: e.str({ devDefault: "" }),
SENTRY_PROJECT: e.str({ devDefault: "" }),
SENTRY_AUTH_TOKEN: e.str({ devDefault: "" }),
CLEVER_SFTP_USERNAME: e.str({ devDefault: "" }),
CLEVER_SFTP_PASSWORD: e.str({ devDefault: "" }),
UPTIME_SHARED_KEY: e.str({ devDefault: "" }),
}),
} And then you use it like this: import {clientEnv} from 'config/clientEnv'
clientEnv.isProduction // type boolean
clientEnv.SENTRY_DSN // type string But I'm not happy with how I have to have two files. Once I get something I'm happy with, we'll consider adding it to new apps. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I usually always strong type my environment variable like this, just to get autocompletion and avoid errors like DATABASE_URL possibly undefined. Could Blitz automatically create this file for you?
Beta Was this translation helpful? Give feedback.
All reactions