秘密值未顯示
P粉218775965
P粉218775965 2024-02-21 17:56:02
0
1
328

我有一個帶有 NextJs 的 SPA,可以向 Google Sheet 提交聯絡表單,該表單在本地工作得很好,但在生產中卻出現了 500 錯誤。 在我的 .env 檔案中,我有以下內容:

NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL=
NEXT_PUBLIC_GOOGLE_PRIVATE_KEY=
NEXT_PUBLIC_GOOGLE_SHEET_ID=

我的 .env.local 檔案中確實有實際的秘密,

這是我的 submit.js 檔案

import { google } from 'googleapis'
require('dotenv-flow').config()

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).send('Only POST requests are allowed!')
  }
// log to see the secret which are visible in local  
  console.log('process.env', process.env)
 console.log(
      'email process with error ',
      process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL
    )
  const body = req.body

  try {
    const auth = new google.auth.GoogleAuth({
      credentials: {
        client_email: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL,
        private_key: process.env.NEXT_PUBLIC_GOOGLE_PRIVATE_KEY?.replace(
          /\n/g,
          '\n'
        ),
      },
      scopes: [
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.file',
        'https://www.googleapis.com/auth/spreadsheets',
      ],
    })
    const sheets = google.sheets({
      auth,
      version: 'v4',
    })

    const submittedAt = new Date().toUTCString()

    const response = await sheets.spreadsheets.values.append({
      spreadsheetId: process.env.NEXT_PUBLIC_GOOGLE_SHEET_ID,
      range: 'A1:F1',
      valueInputOption: 'USER_ENTERED',
      requestBody: {
        values: [
          [
            body.name,
            body.company,
            body.product,
            body.email,
            body.phone,
            submittedAt,
          ],
        ],
      },
    })

   
    return res.status(201).json({
      data: response.data,
    })
  } catch (error) {
    console.log(
      'email process with error ',
      process.env.NEXT_PUBLIC_GOOGLE_CLIENT_EMAIL
    )
// the log fo r this error is down below
    console.log('error.code', error)
    return res.status(error.code).send({ message: error.message })
  }
}

error.code 錯誤:傳入的 JSON 物件不包含 client_email 欄位 error.code 錯誤:傳入的 JSON 物件不包含 client_email 欄位

Ps,秘密是透過aws注入的,並且在雲端監視日誌中可見。

問題1,我的 Dockerfile 中是否需要包含這些機密?

Question2,是否與CSP相關? (尚未實施)

** 更新 我嘗試在 dockerfile 中設定密鑰但不起作用 也嘗試將帶有類別組件的 csp 新增至 _document.js/ 或新增下一個配置,但效果不佳

** 更新 在生產/開發環境中,儘管它是從保險庫注入的,但我無法讀取這些值

P粉218775965
P粉218775965

全部回覆(1)
P粉403804844

我發現 NEXT_PUBLIC_ 不應該在這裡使用,刪除它們後它開始工作。但另一個應該使用前綴的秘密(GTM)沒有載入

更新及解決方案

#事實證明,我需要呼叫 server.js 並請求 env 變數: server.js 是這樣的:

export default function handler(req, res) {
  const publicEnv = Object.keys(process.env)
    .filter((key) => key.startsWith('NEXT_PUBLIC'))
    .reduce((acc, key) => {
      acc[key] = process.env[key]
      return acc
    }, {})

  res.status(200).json(publicEnv)
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!