All api calls return 502 - nextjs 14 - react 18

when i run the site locally, there are no problems connecting to mongodb - issue only when deployed to netlify

site: https://main--ayurmantraa.netlify.app/mongo

enter any text in the text box and press save data - see the console log/network call - it always returns timesout / returns 502 after approx. 10-15 seconds …i also have other calls to database within the app - post login and see they also return 502 after 10-15 seconds…the mongo page is a good example of what i am trying to do in the rest of the app.

i tried making all services background - following the netlify docs using

// This enables the function to run in the background for up to 15 minutes
export const config = {
  type: "experimental-background",
};

----------------within /src/app/functions, the saveData.ts file:

export default async function handler(req: Request) {
  try {
    if (req.method == "POST") {
      const a = await req.text();
      const data = JSON.parse(a);
      const client = new MongoClient(
        "mongodb+srv://<usr>:<pwd>@<myDb>.mongodb.net/etc",
        {
          authSource: "admin",
        }
      );
      await client.connect();

      return await client
        .db("myFirstDatabase")
        .collection("bookings")
        .insertOne(data)
        .then(async (r) => {

          await client.close();
          return NextResponse.json(
            { message: "Data saved successfully!", m2: r, data: data, req: JSON.stringify(req) },
            {
              status: 201,
            }
          );
        })
        .catch(async (e) => {
          await client.close();
          return NextResponse.json(
            { message: e },
            {
              status: 500,
            }
          );
        });
    }
  } catch (error: any) {
    return { statusCode: 500, body: error.toString() };
  }
}
// This enables the function to run in the background for up to 15 minutes
export const config = {
  type: "experimental-background",
};

----------------and using nextjs/react framework, within /src/app/api/saveData/route.ts:

export async function POST(req: Request) {
  if (req.method == "POST") {
    const a = await req.text();
    const data = JSON.parse(a);
    const client = new MongoClient(
     "mongodb+srv://<usr>:<pwd>@<myDb>.mongodb.net/etc",
      {
        authSource: "admin",
      }
    );
    await client.connect();

    return await client
      .db("myFirstDatabase")
      .collection("customer")
      .insertOne(data)
      .then(async (r) => {

        await client.close();
        return NextResponse.json(
          { message: "Data saved successfully!", m2: r, data: data, req: JSON.stringify(req) },
          {
            status: 201,
          }
        );
      })
      .catch(async (e) => {
        await client.close();
        return NextResponse.json(
          { message: e },
          {
            status: 500,
          }
        );
      });
  }

}

any advice on this? thank you for your time !


update 1: also tried the solution to a similar problem here (502 error on production even though the response times are well below 10 seconds) with no luck

Yeah your function seems to be timing out:

Have you tried to refer to: [Support Guide] Why is my function taking long or timing out?

Also you’re using Next.js 14. Next.js Runtime v4 doesn’t support that. Try upgrading to Runtime v5 from the UI.

thanks @hrishikesh i upgraded to runtime v4 and am still facing the same issue. I have tried referring to that link as well but no luck. timing on local for the calls is less than 3 seconds.

i am a bit fuzzy on if the functions are set up properly - although in the build, it shows they are successfuly built:
──────────────────
Functions bundling

Packaging Functions from .netlify/functions-internal directory:

  • ___netlify-server-handler/___netlify-server-handler.mjs
    (Functions bundling completed in 1.9s)
    ──────────────────

i tried timing it using console.time()…but cannot see those logs in the functions section either - i ran netlify build and netlify functions:list locally and can see that they are deployed (and they are) but i am wondering if it is even getting within the function (even though the function logs show that it times out at 10 secs)…reason i say this is because i am not able to see the console.log() stmt outside the try catch - any advice on this?

for reference - the save data function on https://main--ayurmantraa.netlify.app/mongo

export default async function handler(req: Request) {
  console.log("savedata req", JSON.stringify(req));

  try {
    if (req.method == "POST") {
      const a = await req.text();
      const data = JSON.parse(a);
      const client = new MongoClient(
        "mongodb+srv://usr:pwd@[].mongodb.net/etc",
        {
          authSource: "admin",
        }
      );
      console.time("db connect - save data");
      await client.connect();
      console.timeEnd("db connect - save data");
      return await client
        .db("myFirstDatabase")
        .collection("customer")
        .insertOne(data)
        .then(async (r) => {
          // console.log(" req = ", JSON.stringify(req));
          // console.log(" data = ", data);
          await client.close();
          return new NextResponse(
            JSON.stringify({ message: "Data saved successfully!", m2: r, data: data, req: JSON.stringify(req) }),
            {
              status: 201,
            }
          );
        })
        .catch(async (e) => {
          await client.close();
          return new NextResponse(JSON.stringify({ message: e }), {
            status: 500,
          });
        });
    }
  } catch (error: any) {
    return { statusCode: 500, body: error.toString() };
  }
}

i am wondering if i have setup functions correctly…what is the expected response when we go to the function end point? ex: https://ayurmantraa.netlify.app/.netlify/functions/saveData

@hrishikesh any idea?

You’re making a call to /api/saveData, but have a Netlify Function at /.netlify/functions/saveData. Are you trying to use Netlify Functions or Next.js API Handlers?

I have setup both netlify /functions and nextjs /api…I can see that it’s hitting /api on local because of it being a nextjs project. I noticed the build succeeded when I pointed to the /api for netlify functions location but actually no functions were setup. So I created the /functions folder and changed the setup to match the expected header for each function (export handler()) vs the nextjs /api setup (export post() & export get())

After setting up the /functions folder, The functions log shows that it is actually hit and times out. versus beforehand when it would actually return a 404 and nothing would show up in the logs.

Any thoughts ?

Next.js API routes don’t create a separate function. It’s all handled by a single function. The server function still shows it’s being hit and it’s timing out. That looks like some kind of a misconfiguration and we would need a repo to check further.

thanks @hrishikesh - i have sent you a message for next steps on how we can do that

[fixed]

i was missing the second parameter within the function handler - needed context param:

old & incorrect:

export default async function handler(req: Request) {}

correct:

import type { Context } from "@netlify/functions";
export default async function handler(req: Request, context: Context) {}

thanks @hrishikesh - your links and suggestions got me to think about different gaps in my understanding of netlify - i appreciate it.

1 Like