'Typescript says NextJS environment variables are undefined
I'm trying to make social login using 'react-google-login'.
.env in root
NEXT_PUBLIC_GOOGLE_CLIENT_ID=askfjaskf
Ready.tsx
import { GoogleLogin } from "react-google-login";
<GoogleLogin
clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID}
render={(props) => (
<div onClick={props.onClick}>
<div>구글 로그인</div>
</div>
)}
onSuccess={(res) => {
const { profileObj } = res as any;
setStep(AuthStep.AGREE);
}}
onFailure={(res) => {
console.log("Google Error", res);
}}
/>
And in clientId, it says
No overload matches this call. Overload 1 of 2, '(props: GoogleLoginProps | Readonly): GoogleLogin', gave the following error. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. Overload 2 of 2, '(props: GoogleLoginProps, context: any): GoogleLogin', gave the following error. Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2769) index.d.ts(80, 12): The expected type comes from property 'clientId' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<...>'
I don't know why it says it can be undefined. And it works on local but it doesn't work in production deployment. Anyone can help?
Solution 1:[1]
I had the same issue but with different ENV variable, the issue is typescript doesn't know if an ENV variable exists or not.
Check this other question: using process.env in TypeScript
It helped me fixing this problem. Just need to create the environment.d.ts
and declare the global ENV variables as the type you want them to be
declare global {
namespace NodeJS {
interface ProcessEnv {
NEXT_PUBLIC_GOOGLE_CLIENT_ID: string; // this is the line you want
NODE_ENV: 'development' | 'production';
PORT?: string;
PWD: string;
}
}
}
Solution 2:[2]
The answer with declare global { ...
didn't work out for me.
But this one did:
declare namespace NodeJS {
interface ProcessEnv {
JWT_TOKEN: string;
}
}
Add reference to the new file in next-env.d.ts
:
/// <reference types="./environment" />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonni Trev |
Solution 2 | mrkosima |