Created
June 4, 2022 05:31
-
-
Save ArcRanges/a58386858e9ee9b5393f058b6d6d2177 to your computer and use it in GitHub Desktop.
Validate env files so that it fails when a key is missing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// taken from https://dev.to/austinshelby/you-are-reading-environment-variables-the-wrong-way-in-nextjs-45da | |
// helper function | |
const getEnvironmentVariable = (environmentVariable: string): string => { | |
const unvalidatedEnvironmentVariable = process.env[environmentVariable]; | |
if (!unvalidatedEnvironmentVariable) { | |
throw new Error( | |
`Couldn't find environment variable: ${environmentVariable}` | |
); | |
} else { | |
return unvalidatedEnvironmentVariable; | |
} | |
}; | |
export const config = { | |
apiKey: getEnvironmentVariable("API_KEY") | |
}; | |
// usage | |
import { config } from "./config" | |
const url = `https://www.example.com/api/blog?api_key=${config.apiKey}` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment