我的环境变量会暴露给浏览器吗?

Would my environement variables be exposed to the browser?

我编写了一个电子邮件联系表单,想知道在 Next.js' api 文件夹之外重构我的代码是否会危及我的 API键。

除非弄错了——我知道环境变量在以下情况下不会暴露给浏览器:

但是,如果我在 utilities 文件夹中的 api 文件夹之外“提及”我的 process.env.SENDGRID_API_KEY 会发生什么情况,如下所示?浏览器有办法访问它吗?

root
|
├───pages
│   └───api
|       └─────myRoute.ts
├───.env.local
|
├───utilities
│   └───myFunction.ts
│   

/utilities/myFunction.ts

const sendgrid = require("@sendgrid/mail");
sendgrid.setApiKey(process.env.SENDGRID_API_KEY);  // WILL THIS BE AN ISSUE?

export const sendEmail = async (
  name: string,
  email: string,
  message: string
) => {
  const incomingEmail =  `
    From: ${name}\r\n
    Email: ${email}\r\n
    Message: ${message}
  `;

  await sendgrid.send({
    to: process.env.RECEIVING_EMAIL, // WILL THIS BE AN ISSUE?
    from: process.env.SENDGRID_SENDER_EMAIL, // WILL THIS BE AN ISSUE?
    subject: "New message!",
    text: incomingEmail,
    html: incomingEmail.replace(/\r\n/g, "<br>"),
  });
};

pages/api/myRoute.ts

import type { NextApiRequest, NextApiResponse } from "next";

import { sendEmail, acknowledgeReceipt } from "../../utilities/sendGrid"; // Refactors

type Data = {};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const { lang, name, email, message, token } = req.body;


  // Irrelevant validation logic...

  try {

    // Sending e-mail & acknowledging receipt
         await Promise.all([
      sendEmail(name, email, message),
      acknowledgeReceipt(name, email, lang),
    ]);

    return res.status(200).json({ status: "success", msg: "E-mail sent!" });
  } catch (err) {
    // Irrelevant
  }
}

看起来不错。像电子邮件发送实用程序这样的服务器端代码应该只导入到 api 文件中,而不是导入到前端组件文件中,看起来你已经正确地做到了。