NextJS 静态导出指定 .env

发布于 2025-01-20 09:33:26 字数 306 浏览 0 评论 0原文

我有一个带有 Django 后端的 NextJS 应用程序。 NextJS 应用程序是静态导出的,Django 应用程序也会重定向。

导出时,NextJS 默认使用 .env.development,但是在本地开发时,我更喜欢它使用 .env.development 但我不知道如何指定这一点。

当通过 npm run dev 运行时,它使用正确的 .env 但是,关于是否可以选择静态导出的信息有限 - 我刚刚切换根据需要显示文件的内容。

先感谢您!

I have a NextJS app with a Django backend. The NextJS app is statically exported which the Django app redirects too.

When exporting, NextJS uses .env.production by default, however when developing locally I'd prefer it to use .env.development however I can't figure out how to specify that.

When running via npm run dev it uses the proper .env however there is limited info on if this is even possible to choose for the static export - I've just been switching the contents of the files as needed.

Thank you in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

各自安好 2025-01-27 09:33:26

当您运行 next dev 脚本时,next.js 将从 .env.development 加载环境变量

如果您运行 next start 脚本 next.js将从 .env.Production 加载环境变量

Next.js 默认情况下不使用 .env.Production 它使用 .env.local默认。 .env.local 将覆盖 .development 或 .Production 文件上的任何内容。

When you run next dev script, next.js will load the environment variables from .env.development

If you run next start script next.js will load the envrionment variables from .env.production

Next.js does not use .env.production by default it uses .env.local by default. .env.local will override anything on the .development or .production files.

听风念你 2025-01-27 09:33:26

运行命令 next dev (npm run dev) 时,Next.js NODE_ENV 环境变量设置为开发生产用于其他任何内容,例如导出)并将按从上到下的顺序加载以下文件:

  1. 。 env.development.local
  2. .env.local
  3. .env.development
  4. .env

所以不需要指定 应该使用 .env.development - 它只需要存在于您的项目中根目录。

.env.local开发生产环境中加载,但在测试中不加载。

.env 在所有三个环境中加载。

.env*.local 中的变量将覆盖 .env.env.development.env.Production 中的相同变量

When the command next dev (npm run dev) is run, Next.js sets the NODE_ENV environment variable to development (production for anything else, e.g., export) and will load the following files in top-to-bottom order:

  1. .env.development.local
  2. .env.local
  3. .env.development
  4. .env

So there's no need to specify that .env.development should be used — it just needs to exist in your project's root directory.

.env.local gets loaded in both development and production environments, but not in test.

.env gets loaded in all three environments.

Variables in .env*.local will override the same variables in .env, .env.development, and .env.production.

故事与诗 2025-01-27 09:33:26

我发现了一种在 Next.js 应用程序中完成静态导出后动态更改环境变量的解决方案。通常,静态导出后无法更改环境变量,因为它在浏览器中运行。如果浏览器有权访问 process.env,它可能会暴露数据库凭证或 AWS 密钥等敏感信息,从而造成重大安全风险。但是,有一个解决方法涉及使用 process.NEXT_PUBLIC_* 变量。

要实现此解决方案,您需要在提供静态 HTML 文件之前替换 JavaScript 文件中的所有 NEXT_PUBLIC_* 变量。这可以使用 shell 脚本来完成。操作方法如下:

创建包含以下内容的 Replace-env.sh 脚本:

  1. 创建包含以下内容的 replace-env.sh 脚本:
#!/bin/sh
# Function to replace environment variables in files using regex
replace_env_vars() {
  find /usr/share/nginx/html -type f -exec sed -i -E "s|NEXT_PUBLIC_GRAPHQL_ENDPOINT|\"$NEXT_PUBLIC_GRAPHQL_ENDPOINT\"|g" {} \;
}

# Call the function
replace_env_vars

# Execute any additional entrypoint commands, if needed
exec "$@"
  1. 更新 Dockerfile 以合并此脚本:
# Use an appropriate base image
FROM node:16-alpine as builder

# Set the working directory
WORKDIR /app

# Copy the package.json and package-lock.json
COPY package.json package-lock.json ./

# Install dependencies
RUN npm install --force

# Copy the rest of the application code
COPY . .

# Build and export the Next.js application
RUN npm run build && npm run export

# Use a second stage to create a smaller final image
FROM nginx:alpine

# Copy the exported static files to the Nginx web root
COPY --from=builder /app/out /usr/share/nginx/html

# Add a script to replace environment variables in static files
COPY replace-env.sh /docker-entrypoint.d/

# Ensure the script is executable
RUN chmod +x /docker-entrypoint.d/replace-env.sh

# Expose the default Nginx port
EXPOSE 80

# Start Nginx
CMD ["nginx", "-g", "daemon off;"]
  1. 使用适当的容器运行容器环境变量:
docker run -e NEXT_PUBLIC_GRAPHQL_ENDPOINT=http://app-api.example.com -p 80:80 image-name

并且它有效!

I discovered a solution to dynamically change environment variables after static exports are done in a Next.js application. Normally, you can't change environment variables after static export because it runs in the browser. If the browser had access to process.env, it could expose sensitive information like database credentials or AWS keys, creating a significant security risk. However, there's a workaround that involves using process.NEXT_PUBLIC_* variables.

To implement this solution, you'll need to replace all NEXT_PUBLIC_* variables in your JavaScript files before serving the static HTML files. This can be done using a shell script. Here's how:

Create a replace-env.sh script with the following content:

  1. Create a replace-env.sh script with the following content:
#!/bin/sh
# Function to replace environment variables in files using regex
replace_env_vars() {
  find /usr/share/nginx/html -type f -exec sed -i -E "s|NEXT_PUBLIC_GRAPHQL_ENDPOINT|\"$NEXT_PUBLIC_GRAPHQL_ENDPOINT\"|g" {} \;
}

# Call the function
replace_env_vars

# Execute any additional entrypoint commands, if needed
exec "$@"
  1. Update your Dockerfile to incorporate this script:
# Use an appropriate base image
FROM node:16-alpine as builder

# Set the working directory
WORKDIR /app

# Copy the package.json and package-lock.json
COPY package.json package-lock.json ./

# Install dependencies
RUN npm install --force

# Copy the rest of the application code
COPY . .

# Build and export the Next.js application
RUN npm run build && npm run export

# Use a second stage to create a smaller final image
FROM nginx:alpine

# Copy the exported static files to the Nginx web root
COPY --from=builder /app/out /usr/share/nginx/html

# Add a script to replace environment variables in static files
COPY replace-env.sh /docker-entrypoint.d/

# Ensure the script is executable
RUN chmod +x /docker-entrypoint.d/replace-env.sh

# Expose the default Nginx port
EXPOSE 80

# Start Nginx
CMD ["nginx", "-g", "daemon off;"]
  1. Run your container with the appropriate environment variable:
docker run -e NEXT_PUBLIC_GRAPHQL_ENDPOINT=http://app-api.example.com -p 80:80 image-name

And it works!!!

无远思近则忧 2025-01-27 09:33:26

当我做事情时,我注意到 NextJS 使用静态导出对 process.env 做了一些奇怪的事情。 PUBLIC 前缀变量似乎有效,但所有其他变量都被删除。由于 next-auth 似乎与导入 NEXTAUTH_URL 紧密结合,我必须找到一种不同的方法。

/** @type {import('next').NextConfig} */
export default {
  webpack(config) {
    config.plugins.push(new webpack.DefinePlugin({
      'process.env': { NEXTAUTH_URL: '"http://localhost:4040"' },
    }))
    return config
  },
  output: 'export',
}

这有效,注意双引号。 JSON.stringify 无法解析。

但无论如何,它确实没有改变任何东西,因为 next-auth 不支持外部身份验证端点。那好吧...

As I was doing things I noticed that NextJS does something weird to process.env with static exports. PUBLIC prefixed variables seem to work but all others are removed. And since next-auth seems to be tightly coupled with importing NEXTAUTH_URL, I had to find a different way.

/** @type {import('next').NextConfig} */
export default {
  webpack(config) {
    config.plugins.push(new webpack.DefinePlugin({
      'process.env': { NEXTAUTH_URL: '"http://localhost:4040"' },
    }))
    return config
  },
  output: 'export',
}

And this worked, notice the double quotes. JSON.stringify failed to parse.

But anyway, it really didn't change anything as next-auth doesn't support external auth endpoints. Oh well...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文