如何获得下一个.客户端的JS环境变量



我有一个Next。我将使用docker部署的Js应用程序。我在docker文件和docker-compose.yaml中传递我的环境变量。下一版本:12.1.6

Dockerfile

# Install dependencies only when needed
FROM node:16-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
# If using npm with a `package-lock.json` comment out above and use below instead
# COPY package.json package-lock.json ./ 
# RUN npm ci
# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1
RUN yarn build
# If using npm comment out above and use below instead
# RUN npm run build
# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
ENV NEXT_PUBLIC_BASE_URL example --> I'm stating it here. Example is not my value, it just takes space.

# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
# Automatically leverage output traces to reduce image size 
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT 3000
CMD ["node", "server.js"]

docker compose.yaml

version: '3'
services:
frontend:
image: caneral:test-1
ports:
- '3000:3000'
environment:
- NEXT_PUBLIC_BASE_URL=https://example.com/api

我正在使用以下命令进行构建:

docker build -t caneral:test-1 .

然后我运行docker compose:

docker-compose up -d

虽然我可以在服务器端访问NEXT_PUBLIC_BASE_URL值,但无法在客户端访问它。它返回undefined。我不应该因为将其定义为NEXT_PUBLIC而达到它吗?这在官方文件中有说明。

如何在客户端获取环境变量?

详细信息,你有:

  1. 您的.env文件。(我不确定docker文件将如何影响逻辑(
  2. 您的next.config.js文件

服务器端可以访问这两个文件。

客户端没有访问.env文件的权限。

你能做什么:

next.config.js文件中,您可以声明一个variable,其中value是您的process.env值。

const baseTrustFactor = process.env.trustFactor

重要事项:不要向客户端公开您的私人信息(密钥/令牌等(。

如果你需要比较代币,你可以:

  1. 从后端发送它们(来自NodeAPI或类似(
  2. next.config.js中设置条件,例如:

const baseTrustFactor = process.env.trustFactor == '21' ? true : false

最新更新