首页 > 解决方案 > 如何在 Next.js 中根据环境变量设置基本 URL?

问题描述

我在 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 和部署中的后端获取内容。当我尝试加载图像时,问题就出现了,该路径应该是基本 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 生成对于代码的某些部分是可以的,而对于其他部分则不行。

部署的构建命令是: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,
    },
  };
};

标签: javascriptnode.jsenvironment-variablesnext.jsdigital-ocean

解决方案


默认情况下,出于安全考虑,不会向浏览器Next.js公开所有变量。process.env.X

为了向浏览器公开环境变量,它NEXT_PUBLIC_的名称中必须有前缀。

在您的情况下,重命名API_URLNEXT_PUBLIC_API_URL并使用它。

欲了解更多信息:https ://nextjs.org/docs/basic-features/environment-variables


推荐阅读