[英]Getting environment variables to work in next js and netlify
I have deployed a next js application to netlify using git and I have a .env.local
file that stores the backend route url that I use everywhere throughout the app when making fetch requests.我已经部署了下一个 js 应用程序来使用 git 进行 netlify,并且我有一个
.env.local
文件,用于存储我在整个应用程序中在发出获取请求时使用的后端路由 url。 The problem is that after deployment the process.env.NEXT_PUBLIC_BACKEND_ROUTE returns undefined.问题是在部署之后 process.env.NEXT_PUBLIC_BACKEND_ROUTE 返回 undefined。
The .env.local
file: .env.local
文件:
NEXT_PUBLIC_BACKEND_ROUTE=https://[the name of the url].herokuapp.com/
An example of a page using the environment varible:使用环境变量的页面示例:
import axios from 'axios';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
export default function Home() {
const router = useRouter();
useEffect(() => {
axios
.get(`${process.env.NEXT_PUBLIC_BACKEND_ROUTE}/findAllPictures`)
.then((doc) => {
const arr = doc.data;
if (arr.length !== 0) {
const mappedArr = arr.map((obj) => {
return obj.id;
});
const amount = mappedArr.length;
const rand = Math.floor(Math.random() * amount);
const routeId = mappedArr[rand];
router.push(`/view/${routeId}`);
}
});
}, [null]);
return <div></div>;
}
There are two possibilities I see我看到有两种可能性
your .env.local
file is not in root您的
.env.local
文件不在 root 中
Some weird formatting issue is going on with the variables.变量出现了一些奇怪的格式问题。 In that case, try surrounding your variable in quotes:
在这种情况下,尝试用引号将变量括起来:
NEXT_PUBLIC_BACKEND_ROUTE="https://[the name of the url].herokuapp.com/" NEXT_PUBLIC_BACKEND_ROUTE="https://[url 名称].herokuapp.com/"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.