我已经编码了一个电子邮件联系人表单,想知道在Next.js'
api文件夹之外重构代码是否会危及我的api密钥。
除非弄错了——我知道环境变量不会暴露在浏览器中,如果它们是:
- 是否不前缀为
NEXT_PUBLIC_
- 在框架的
api
文件夹中使用 - 在
getStaticProps
、getStaticPaths
和getServerSideProps
服务器端函数中使用
然而,如果我";提到";我的process.env.SENDGRID_API_KEY
在utilities
文件夹中的api
文件夹之外,如下所示?浏览器有任何方法可以访问它吗?
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}rn
Email: ${email}rn
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(/rn/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文件中,而不导入到前端组件文件中,看起来您已经正确地导入了。