Function returns 502 Gateway Error

site name: gemsim.net

I have a couple functions for CRUD with a mongoDB, e.g., create_feature.mts

import { Context } from '@netlify/functions'
import { MongoClient } from "mongodb"

const MONGODB_URI = process.env.MONGODB_URI!
const client = new MongoClient(MONGODB_URI)
const clientPromise = client.connect()

export default async (request: Request, context: Context) => {
  try {
    const { description } = await request.json()
    const db = (await clientPromise).db(process.env.MONGODB_DATABASE)
    const features = db.collection("features")
    console.log("Inserting feature request:", description)
    const result = await features.insertOne({
      description,
      timestamp: new Date()
    })
    console.log("Feature request inserted with ID:", result.insertedId)
    return new Response(JSON.stringify({ insertedId: result.insertedId }), {
      headers: { "Content-Type": "application/json" }
    })
  } catch (error) {
    console.error("Error inserting feature request:", error.toString())
    return new Response(error.toString(), {
      status: 500,
    })
  }
}

These functions run fine when tested locally, but got 502 error on deployed site. I don’t see any invocation logs. I’ve also checked the environment vars are set correctly.

How to debug this issue?

@xzwang2005 By ‘invocation logs’, do you mean the Function logs?

If the function is running, I’d expect to see it shown in the logs.

yep, all I see from the log is this, seems the function is running:

The error was actually: “error decoding lambda response: error decoding lambda response: unexpected end of JSON input”

And here’s the request:

hmm, I’ve added a Hello function, which works in prod. But I still don’t see the logs in Netlify UI.

It says timeout. Check: [Support Guide] Why is my function taking long or timing out?

Thanks for the info.

The time out occurred when the function was connecting to MongoDB. After allow network access from anywhere (in MongoDB), the function work now. Is there any security risk for this approach?

Yes, anyone can connect to your database if they have the username and password.