Framework/Next.js

[Next.js] 클라이언트에서 process.env가 undefined를 반환할 때

taedonn 2023. 11. 22. 14:03
728x90

 

클라이언트에서 process.env가 undefined를 반환하는 이유?

Next.js는 환경 변수를 Node.js 환경에서만 읽을 수 있게 제한하고 있다. 브라우저에서는 접근할 수 없기 때문에 undefined가 뜨는 것.

.env

TEST_URL="https://test.com"

index.js

export default function Index() {
	console.log("process.env.TEST_URL" + process.env.TEST_URL);
}

console

 

 

클라이언트에서 필요한 경우가 있을까?

거의 없긴 하지만 100%라고 확신할 수는 없다. 예를 들어 카톡으로 웹페이지 공유 기능을 구현할 때 카카오 개발자 페이지에서 자바스크립트 key를 발급받고 발급받은 키를 프론트에서 함수를 실행할 때 넣어줘야 된다. 이런 식으로 라이브러리를 사용할 때 가끔 클라이언트에서 환경 변수를 처리해야 되는 경우가 있다.

 

 

해결 방법 1. getServerSideProps() 안에 넣고 파라미터로 전달

index.js

const Index = ({params}) => {
	console.log("process.env.TEST_URL : " + params.url);
}

export async function getServerSideProps(ctx) {
    return {
        props: {
            params: {
                url: process.env.TEST_URL
            }
        }
    }
}

export default Index;

console

 

 

해결 방법 2. 환경 변수 앞에 NEXT_PUBLIC_ 넣기

Next.js 9.4 버전 이후부터는 환경 변수 앞에 NEXT_PUBLIC_을 붙히면 클라이언트에서도 읽을 수 있게 업데이트 됐다고 한다.

.env

NEXT_PUBLIC_TEST_URL="https://test.com"

index.js

export default function Index() {
	console.log("test url : " + process.env.NEXT_PUBLIC_TEST_URL);
}

console

 

9.4 이전 버전이거나 위에 방법이 안된다면?

위에 방법이 안되면 next.config.js 안에 환경 변수를 선언하는 것도 시도해 볼 수 있다. Next.js에서 더 이상 권장하지 않는 방식이라고 하지만.. 안되면 뭐라도 해야지..

next.config.js

module.exports = {
    env: {
    	TEST_URL: process.env.TEST_URL,
    }
}

 

 

참고

Configuring: Environment Variables | Next.js

 

Configuring: Environment Variables | Next.js

Learn to add and access environment variables in your Next.js application.

nextjs.org

 

javascript - next.js environment variables are undefined (Next.js 10.0.5)

 

next.js environment variables are undefined (Next.js 10.0.5)

I am coding a website with Next.js and I tried to add google Tag Manager. I followed the tutorial on the Next.js Github example but for some reasons I can't access to my environment variables. It ...

stackoverflow.com

 

728x90