Netlify serverless function returning 502

Okay, so I’m trying to set up a simple email form on my website, the user enters a message, and then an email is sent with said message. Locally, everything works fine, but on the live version of my website, I get a 502 error. I’ve already looked around the forums and added various things to my configuration but it still doesn’t work. Is it possible that my env variables aren’t being loaded on the server? What am I missing here?

If out of curiosity, my domain name is https://rohitkisto.dev, contact form is at the bottom.

Here are some screen shots of my configuration.

This is part of my frontend, where the serverless function gets called.

const sendMessage = async ({ message }: FormInputs) => {
    const { status } = await fetch("./.netlify/functions/send-message", {
      method: "POST",
      body: JSON.stringify({
        message
      })
    });

    if (status !== 200) {
      throw new Error(`Error ${status} occured while sending message.`);
    }

    reset();
  };

Here’s my serverless function.

import type { Handler } from '@netlify/functions';
import fetch from "node-fetch";

const handler: Handler = async ({ body }) => {
  if (body === null) {
    return {
      statusCode: 400,
      body: JSON.stringify("Payload required")
    };
  }

  const { message } = JSON.parse(body) as {
    message: string
  }

  const { status, statusText } = await fetch(
    `./.netlify/functions/emails/subscribed`,
    {
      headers: {
        "netlify-emails-secret": process.env.NETLIFY_EMAILS_SECRET as string,
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Origin": process.env.NETLIFY_URL as string
      },
      method: "POST",
      body: JSON.stringify({
        from: "There is an email here",
        to: "There is an email here",
        subject: "New Message",
        parameters: {
          message
        },
      }),
    }
  );


  return {
    statusCode: status,
    body: JSON.stringify(status === 200 ? "Message sent!" : `An error occured sending email!\n${statusText}`)
  }
}

export { handler };

My netlify.toml.

[build]
command = 'npm run build'
functions = 'netlify/functions'
publish = 'dist'

[[plugins]]
  package = "@netlify/plugin-emails"

If there’s anything else I can provide please let me know :slight_smile:

Hi, could you provide your function log? This is also a common error with many proposed solutions. I also recommend you search the error through the forums and try some of the proposed solutions to see if this helps.

1 Like

I managed to fix it. Three things:

  1. Make sure node-fetch is installed (I know in the post it’s there but when I first got the issue I didn’t have it).
  2. Make sure your .env file is loaded. Running netlify env:import .env or just import them on your project dashboard.
  3. Ensure that you’re calling the correct URL. Originally, I have the following line in my serverless function:
const { status, statusText } = await fetch(`./.netlify/functions/emails/subscribed`, ...)

When it should’ve been:

const { status, statusText } = await fetch(`${process.env.NETLIFY_URL}/.netlify/functions/emails/subscribed`, ...)

where NETLIFY_URL is a variable I have in my .env file.

Hope this helps someone!

Thanks for sharing your solution @rohitrtk !

1 Like