如何在Next.js中根据环境变量设置基本URL?

mum43rcc  于 2023-06-22  发布在  其他
关注(0)|答案(2)|浏览(249)

我在DigitalOcean上部署了一个Strapi后端和Next.js前端应用程序。在DigitalOcean上,为前端设置了一个环境变量:API_URL = ${APP_URL}/api
我获取这个变量来生成基本url:

// constants.js
export const BASE_URL =
  process.env.NODE_ENV === "production"
    ? process.env.API_URL
    : "http://localhost:1337";

它似乎工作得很好,应用程序从localhost和deploy中的后端获取内容。问题来了,当我试图加载图像的路径应该是基本URL和提取的相对路径的连接。我为此创建了一个utilitz函数:

// utilities.js
import { BASE_URL } from "./constants";
export const getImageURL = (relPath) => `${BASE_URL}${relPath}`;

当我将这个函数用于html img标记时,它会在dev和prod环境中加载:
<img src={getImageURL(homePage.Hero[0].Image.url)} />
但是当我尝试在同一个组件中为div设置背景时,基本url是未定义的,图像不会出现在部署的站点中(在localhost上运行良好)。
我不知道为什么URL生成对代码的某一部分是OK的,而对另一部分则不OK。
deploy的build命令是:yarn build && next export -o _static
下面是完整的组件:

import styles from "../styles/Home.module.css";
import { getImageURL } from "../lib/utilities";
import { useEffect } from "react";
import { BASE_URL } from "../lib/constants";

export default function Home({ homePage }) {
  console.log(BASE_URL); // undefined

  useEffect(() => {
    if (window) {
      console.log(BASE_URL); // undefined
      document.getElementById("container").style.backgroundImage = `url('${getImageURL(homePage.Hero[0].Image.url)}')`; // url is undefined/realtivepath
    }
  });

  return (
    <div id="container">
      <img src={getImageURL(homePage.Hero[0].Image.url)} />
    </div>
  );
}

export const getStaticProps = async () => {
  const res = await fetch(`${BASE_URL}/home-page`); // OK for dev and deploy
  const homePage = await res.json();
  return {
    props: {
      homePage,
    },
  };
};
pod7payv

pod7payv1#

默认情况下,出于安全考虑,Next.js不会向浏览器公开所有process.env.X变量。
为了向浏览器公开环境变量,它的名称必须有一个前缀NEXT_PUBLIC_
在本例中,将API_URL重命名为NEXT_PUBLIC_API_URL,并使用它。
更多信息:https://nextjs.org/docs/basic-features/environment-variables

ztigrdn8

ztigrdn82#

我是这样做到的

const fetchProducts = async () => {
  const response = await fetch(`${process.env.NEXT_PUBLIC_APP_API_ENDPOINT}/products`);
  const data = await response.json();
  setProducts(data.products);
};

相关问题