Home > Mobile >  Would my environement variables be exposed to the browser?
Would my environement variables be exposed to the browser?

Time:10-04

I have coded an e-mail contact form and was wondering if refactoring my code outside of Next.js' api folder could compromise my API key.

Unless mistaken — I am aware that environmental variables aren't exposed to the browser if they:

  • Aren't prefixed by NEXT_PUBLIC_;
  • Are used within the api folder of the framework;
  • Are used within the getStaticProps,getStaticPaths and getServerSideProps server-side functions.

However, what would happen if I "mentioned" my process.env.SENDGRID_API_KEY outside of the api folder in a utilities folder as shown below? Would the browser have any way of accessing it?

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
  }
}

CodePudding user response:

It looks fine. Server side code like the email sending utility should only be imported into api files, not into frontend component files, which it looks like you are already doing that correctly.

  • Related