Approach 1: Explicitly Casting
To handle environment variables, a straightforward method is to cast them as strings when accessing them. This approach will function correctly assuming the variables are properly defined. However, failure to set them in the future may result in errors.
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID as string,
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
})
Approach 2: Type Assertion
An alternative is to ensure that environment variables are declared before using them. While effective, this method can become cumbersome. TypeScript will recognize any values that are not undefined within this block of code. Nonetheless, this approach shares similar issues with the first option.
if (
process.env.GOOGLE_CLIENT_ID === undefined ||
process.env.GOOGLE_CLIENT_SECRET == undefined
) {
throw new Error('Invalid env vars');
}
Approach 3: Typed Environment Variables
In my view, this is the most optimal choice. I highly recommend utilizing the t3-env package. By doing so, you gain access to type-safe environment variables.