Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ArcRanges/a58386858e9ee9b5393f058b6d6d2177 to your computer and use it in GitHub Desktop.
Save ArcRanges/a58386858e9ee9b5393f058b6d6d2177 to your computer and use it in GitHub Desktop.
Validate env files so that it fails when a key is missing
// 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