I'm trying to use the Resend API to create a simple contact form in NextJS. To do this, I created a server action to connect to the API and send the email. When run the code, I get the following CORS error:
Access to fetch at 'https://api.resend.com/emails' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here's my sendEmail
function in /app/_actions.ts:
export async function sendEmail({email, name, org, message}: {email: string, name: string, org?: string, message?: string}){
const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KEY);
const myEmail = process.env.NEXT_PUBLIC_EMAIL || '';
try {
const data = await resend.emails.send({
from: myEmail,
to: myEmail,
subject: `${name}, from ${org}`,
html: `${email}: ${message}`
});
return { success: true , data };
} catch(error) {
return { success: false , error };
}
}
And here's the code in my .tsx component that calls this action:
const submitEmail = async ({email, name, org, message}: {email: string, name: string, org: string, message: string}) => {
const result = await sendEmail({email, name, org, message})
.then((res) => {
console.log(res);
})
}
I've found that I may have to modify my next.config.ts
file, but I wasn't able to find anything that worked.
I would greatly appreciate any help, thanks!
After reading Resend How do I fix CORS issues?, I found that all I had to do was add
"use server";
in the beginning of my/app/_actions.ts
file.