【发布时间】:2021-11-24 01:52:04
【问题描述】:
我编写了一个电子邮件联系表单,想知道在 Next.js' api 文件夹之外重构我的代码是否会危及我的 API 密钥。
除非弄错了——我知道环境变量不会暴露给浏览器,如果它们:
-
不是以
NEXT_PUBLIC_为前缀; - 在框架的
api文件夹中使用; - 在
getStaticProps、getStaticPaths和getServerSideProps服务器端函数中使用。
但是,如果我在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
}
}
【问题讨论】:
标签: node.js next.js environment-variables sendgrid