I am trying to figure out how to secure a send grid api post request in my nex tjs application.
I have the following:
export const sendEamil = async <T>(data: T) =>
await fetch("/api/send-email", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
},
body: JSON.stringify(data),
});
which is used inside my component like so:
const onSubmit: SubmitHandler<FormValues> = async (data) => {
try {
const res = await sendEamil(data);
if (res.status === 200) {
toast.success("Your message has been sent!");
reset();
}
} catch (err) {
toast.error("Something went wrong. Please try again later.");
}
};
based on this article => https://docs.sendgrid.com/api-reference/how-to-use-the-sendgrid-v3-api/authentication I have applied the Authorization header but the API KEY is now exposed.
I am no familiar with authorising api requests but exposing an API key doesn’t feel right. (It’s visible in the network tab)
If have your
sendEmail
in an API route or Server Component as the name of the env variable would suggest, it will not be exposed to the client so you are safe there.