#Help with api route

21 messages · Page 1 of 1 (latest)

viscid marlin
#

I'm trying to send a transactional mail with resend.

It works great locally, but on live i cant even seem to trigger my api route.

Those console.log I've put in there, dont even trigger on my vercel deployment but they work great on local dev and build environment

I hope someone can help me out here

This is my app/api/resend/route.ts

import { NextRequest } from 'next/server';

export const dynamic = 'force-dynamic';

const resendAPIKey = process.env.RESEND_API_KEY;

if (!resendAPIKey) {
  throw new Error('RESEND_API_KEY is not defined');
}

export async function POST(req: NextRequest) {
  const { email, beat } = await req.json();

  console.log('Sending email to', email);

  const res = await fetch('https://api.resend.com/emails', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${resendAPIKey}`
    },
    body: JSON.stringify({
      from: '[email protected]',
      to: `${email}`,
      subject: 'Dein Demo Download ist da! 🎉',
      attachments: [
        {
          filename: beat.name,
          path: beat.url
        }
      ],
      html: `
        <h1>Dein Demo Download ist da! 🎉</h1>
        <p>Hey, du hast dir gerade einen Demo Download von CatchBeatz gesichert! 🎉</p>
        <p>Dein Download: <a href="${beat.url}">${beat.name}</a></p>
        <p>Ich hoffe, dass dir der Beat gefällt! 🎵</p>
        <p>Wenn du Fragen hast, schreib mir einfach eine E-Mail an <a href="mailto:xxx">
      `
    })
  });

  const data = await res.json();
  console.log('Email sent', data);

  if (res.ok) {
    return Response.json(data);
  }
}

quartz carbonBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

tropic cloak
#

Maybe it is a dumb question but have you set your environment variable RESEND_API_KEY on vercel ?

#

and after you set environment variable, you must re-deploy your app

viscid marlin
#

Yes i did, i‘ve also have a error throwing in case i dont have it set

I think otherwise i would also get a response on vercel when trying to send the request but i seems to not even try

waxen obsidian
#

How are you calling the route handler / endpoint

#

show the fetch

viscid marlin
#

Yes 1 sec

#
interface SendDemoDownloadEmailProps {
  email: string;
  beat: {
    name: string;
    url: string;
  };
}

const BASE_URL = 'http://localhost:3000';
const API_URL = `${BASE_URL}/api/resend`;

export const sendDemoDownloadEmail = async (props: SendDemoDownloadEmailProps) => {
  const { email, beat } = props;

  try {
    const res = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email,
        beat
      })
    });

    if (res.ok) {
      const data = await res.json();
      return data;
    }
  } catch (error) {
    console.error(error);
  }
};
waxen obsidian
#

https://nextjs-faq.com/fetch-api-in-rsc
TL;DR: Don't fetch your own endpoints in server components. If you find yourself doing that, you are most likely doing something wrong. Use the logic of the endpoint directly in your server component

#

Link contains all info why it works locally and not in deployment

viscid marlin
#

i gotta say i tried to use resend like in this example, inside of a sercer action and it also worked locally but not on production

const { data, error } = await resend.emails.send({
    from: 'Acme <[email protected]>',
    to: ['[email protected]'],
    subject: 'Hello world',
    react: EmailTemplate({ firstName: 'John' }),
  });
viscid marlin
viscid marlin
waxen obsidian
#

yea

#

you were mixing some concepts up

#

you can go with route handler and fetching it form a client component

#

or no route handler and do it directly form a server component

#

Depends if you need data from state. I guess you'll need data like firstName from a form or whatever eventually

viscid marlin
#

my main issue was actually not setting another .env access_token which was needed for a function that ran before the email send happened. + I reverted the route i created and now fetch inside of the server Action directly.

Now it works in local and production, I really need to throw errors more in case i forget to set an .env variable

thank you a lot @waxen obsidian

waxen obsidian