【问题标题】:Env variables in nextjsnextjs 中的环境变量
【发布时间】:2021-09-08 16:21:05
【问题描述】:

我一直在尝试了解如何在 nextjs 中处理环境变量,但我仍然不明白。我只是想从下面的代码中隐藏我的 API 密钥。据我了解,我只能通过使用 getServerSideProps 或 getStaticProps 来做到这一点。如果是这样的话,尽管我仍然不知道应该如何相应地修改我的代码

       import { createContext, useState, useEffect } from 'react';

const WeatherContext = createContext({
  searchLocation: (input) => {},
  btnHandler: (input) => {},
  weather: '',
  isLoading: true,
});

export function WeatherContextProvider(props) {
  const [weather, setWeather] = useState({});
  const [city, setCity] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [unit, setUnit] = useState('metric');
  const [searchInput, setSearchInput] = useState('');
  

  const btnHandler = () => {
    if (unit === 'metric') {
      setUnit('imperial');
    } else {
      setUnit('metric');
    }
  };

  const searchLocation = async (input = searchInput, units = unit) => {
    if (loading) {
      input = 'London';
    }
    try {
      const firstResponse = await fetch(
        `https://api.openweathermap.org/data/2.5/weather?q=${input}&units=${units}&appid=KEY`
      );
      
      const firstData = await firstResponse.json();
      if (!firstResponse.ok) {
        setError(true);
        throw new Error('Something went wrong');
      }

      let lon = firstData.coord.lon;
      let lat = firstData.coord.lat;

      const response = await fetch(
        `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=${units}&exclude=&appid=KEY`
      );
      const data = await response.json();

      if (!response.ok) {
        setError(true);
        throw new Error('Something went wrong');
      }
      setWeather(data);
      setCity(firstData.name + ', ' + firstData.sys.country);
      setSearchInput(firstData.name);
      setLoading(false);
      setError(false);
    } catch (error) {
      setError(error.message);
      console.log(error);
    }
  };

  useEffect(() => {
    searchLocation();
  }, [unit, searchInput]);

  const context = {
    searchLocation: searchLocation,
    city: city,
    weather: weather,
    isLoading: loading,
    error: error,
    btnHandler: btnHandler,
    unit: unit,
    searchInput: searchInput,
  };

  return (
    <WeatherContext.Provider value={context}>
      {props.children}
    </WeatherContext.Provider>
  );
}

export default WeatherContext;

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

不幸的是,如果您希望从客户端访问 api,那么您将公开 env 变量,而从 getServerSideProps 或 getStaticProps 进行的任何调用都可以在服务器端保持 env 变量私有。

记住,在你的 react 代码中创建一个将在客户端公开/访问的环境变量时,你需要在环境变量名称前面加上NEXT_PUBLIC_,这也是非常重要的,这样 nextjs知道在客户端允许环境变量。

话虽如此,您处理 api 关键情况的最佳方法似乎是在项目的根目录中创建一个 .env 文件并添加类似 NEXT_PUBLIC_API_KEY=insert-your-api-key-here 的内容。

如果您绝对需要将此 api 密钥保密,我认为您最好的做法是在您的页面文件夹 (/pages/[slug].jsx) 和该页面的 getServerSideProps 中创建一个动态路由,您可以使用在服务器端进行 api 调用的参数数据,这将使您的 api 密钥包含在服务器端。

【讨论】:

    【解决方案2】:

    这是一个很好的参考视频,很好地解释了环境变量https://www.youtube.com/watch?v=vS86x_e0zBk,Next.js 有一些最好的文档https://nextjs.org/docs/basic-features/environment-variables

    根据以往的经验,最好最简单的方法是通过.env.local 文件。从那里你可以设置你想成为服务器端、客户端等的变量。

    【讨论】:

      【解决方案3】:

      创建一个.env 文件并在其中声明您的 API 密钥值。

      API_KEY: 'YOUR_KEY'
      

      像这样调用next.config.js文件中的环境变量:

      module.exports = ({
          env: {
              API_KEY: process.env.API_KEY
          }
      })
      

      最后在你的项目中使用你想要的环境值,像这样{process.env.API_KEY}

      【讨论】:

      • 请注意,这仅与 9.4 版本之前的 Next.js 相关。
      • 是的,现在 Next.js 自带了对环境变量的内置支持,所以 next.config.js 部分没有用了!
      猜你喜欢
      • 2021-09-13
      • 2021-08-15
      • 1970-01-01
      • 2019-07-24
      • 2020-11-25
      • 1970-01-01
      • 2021-01-26
      • 2021-11-26
      相关资源
      最近更新 更多