roudlek
roudlek

Reputation: 385

Resend email doesn't work in production environement with next js, but works in development

import { EmailTemplate } from "@/components/email-template";
import { Resend } from "resend";

const resend = new Resend("myApiKey"); // this works only in dev
// const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KEY); // this doesnt at all
// const resend = new Resend(process.env.RESEND_API_KEY); // this doesnt at all


export async function POST(request: Request) {
  const { name, numberPhone, address, productsInCart} = await request.json();

  try {
    const data = await resend.emails.send({
      from: "Contact Form <[email protected]>",
      to: ["[email protected]"],
      subject: "New order from your ecommerce app.",
      react: EmailTemplate({
        name: name,
        numberPhone: numberPhone,
        address: address,
        productsInCart: productsInCart
      }),
    });

    return Response.json(data);
  } catch (error) {
    return Response.json({ error });
  }
}

  const handleSendDataViaEmailResend = async () => {
    // console.log(JSON.stringify(formData));
    try {
      setLoading(true); // Set loading to true when starting the async operation

      const response = await fetch("/api/send", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          name: formData.name,
          email: formData.email,
          numberPhone: formData.numberPhone,
          address: formData.address,
          productsInCart: productsInCart,
        }),
      });

      if (response.ok) {
        console.log("Order placed successfully!");
        router.push("/success");
        // Handle success, e.g., redirect to a thank you page
      } else {
        console.error("Error placing order:", response.statusText);
        // Handle error, show an error message to the user
      }
    } catch (error) {
      console.error("Error placing order:", error);
    } finally {
      setLoading(false); // Set loading back to false after the async operation completes
    }
  };

Tried both process.env.RESEND_API_KEY and EXT_PUBLIC_RESEND_API_KEY I have the variable in env.local file

The crazy thing that it works on development but not in vercel production deployment the second part is api call i could have some mistakes in my code i'm a near medium programmer as i think i want this to work when it's deployed as well

Upvotes: 4

Views: 1035

Answers (3)

roudlek
roudlek

Reputation: 385

It was just a resend version problem, i just updated it the last one and now it works fine !

Upvotes: 0

jerome
jerome

Reputation: 411

I fixed this issue for my use case by changing the Request to NextRequest and also adding my API key to the next.config.js file.

/** @type {import('next').NextConfig} */
const nextConfig = {
    env: {
      RESEND_API_KEY: process.env.RESEND_API_KEY,
    },
  }
  
  module.exports = nextConfig

Other than that, I'm using await the same as you. I hope this helps

Upvotes: 0

M&#225;rio Viana
M&#225;rio Viana

Reputation: 1

These days I faced the same issue - it turns out that I had a wrong configuration on my next.config.mjs file. Previously I had the file like this:

const nextConfig = {
  output: "export", // Outputs a Single-Page Application (SPA).
  distDir: "./dist", // Changes the build output directory to `./dist/`.
  webpack: (config) => {
    config.resolve.fallback = {fs: false, net: false, tls: false};
    config.externals.push("pino-pretty", "encoding");
    return config;
  },
};

export default nextConfig;

By removing the output and disDir settings I was able to send emails.

Important info about output setting:

  • undefined: The default build output, .next directory, that works with production mode next start or a hosting provider like Vercel
  • standalone: A standalone build output, .next/standalone directory, that only includes necessary files/dependencies. Useful for self-hosting in a Docker container.
  • export: An exported build output, out directory, that only includes static HTML/CSS/JS. Useful for self-hosting without a Node.js server.

This was happening because I had set the output to export. Sending emails requires a Node.js server, which is not included with the export setting. As a result, I was unable to send emails with this configuration.

Current next.config.mjs

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.resolve.fallback = {fs: false, net: false, tls: false};
    config.externals.push("pino-pretty", "encoding");
    return config;
  },
};

export default nextConfig;

With this I'm not facing any issue. Hope it helps someone.

Upvotes: 0

Related Questions