Error while using netlify functions locally

Hi

Here’s my netlify site name : vpawards-vue

I’ve just got started with netlify cli and am using netlify dev to test my site locally… am very excited as I want to be able to test the serverless functions locally… so I did everything based on the requirements for installing the cli and added the site id with netlify link and everything works fine…:-)…

Except for the netlify functions… which seems to give me the error below… it’s a simple function that’s connecting to a mongo client and saving a document.

{"level":"error","message":"End - Error:"}
{"errorMessage":"Task timed out after 10.00 seconds","errorType":"TimeoutError","level":"error","stackTrace":["new TimeoutError (C:\\Users\\alimb\\AppData\\Roaming\\npm\\node_modules\\netlify-cli\\node_modules\\lambda-local\\build\\lib\\utils.js:112:28)","Context.<anonymous> (C:\\Users\\alimb\\AppData\\Roaming\\npm\\node_modules\\netlify-cli\\node_modules\\lambda-local\\build\\lib\\context.js:110:19)","listOnTimeout (node:internal/timers:557:17)","processTimers (node:internal/timers:500:7)"]}
Response with status 500 in 10434 ms.

On the browser’s console I get this error

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I am not sure how else to describe the error in detail… except that it works fine on the live site. If there’s anything more I can provide to you, I’d be happy to. Could you please help me with this so that I can start using netlify locally?

Here’s the function code that’s causing the issue locally but not on the live site…

const dotenv = require('dotenv')
dotenv.config()
const { MongoClient, ServerApiVersion } = require('mongodb')

const DB = process.env.VUE_APP_DATABASE.replace(
  '{%PASSWORD%}',
  process.env.VUE_APP_DATABASE_PASSWORD
)

const client = new MongoClient(DB, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1,
})

exports.handler = async function (event, context) {
  const user = JSON.parse(event.body)

  if (user._id) user._id = null

  console.log('user', user)

  await client.connect()
  const db = client.db()

  try {
    const newUser = await db.collection('users').insertOne({ ...user })

    client.close()
    return {
      statusCode: 200,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        status: 'success',
        user,
        newUserId: newUser?.insertedId.toString(),
      }),
    }
  } catch (error) {
    console.log(error)
    return {
      statusCode: 200,
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        status: 'fail',
        message: error.message,
        error,
      }),
    }
  }
}

Regards,
Alim

HI @alimbolar

The error message shows the function did not complete in the permitted time of 10 seconds.

Check all environment variables are set correctly. Add extra logging to the function to see what is happening.

Hi @coelmay

Thanks for the prompt response…:-)…

I had sent a message earlier and then deleted it as there was some issues with my testing.

I seem to have resolved the issue…:-)… but I am not sure if it’s because of what I did… so just wanted to confirm.

This is my netlify.toml file

[functions]
directory="functions"
node_bundler="esbuild"


[[redirects]]
from="/api/*"
to="/.netlify/functions/:splat"
status=200

So on checking the path of the ‘.netlify/functions’ folder I realised that the path was ‘.netlify/functions-serve’… so I changed the folder name to make it ‘./netlify/functions’ and it seemed to work…

however I noticed that on running ‘netlify dev’ the same folder ‘.netlify/functions-serve’ was recreated… so i have my regular ‘functions’ folder at the root… plus the folder I renamed to ‘.netlify/functions’ and the new folder ‘./netlify/functions-serve’ …

What do I need to do for this?

I am assuming all my updates would be stored in the ‘.netlify/functions-serve’ file… so would I have to rename the folder every time I test?

One more question… if ‘netlify dev’ something I should be using all the time… I mean is it a replacement for ‘npm run dev’ or is it something I should use to test only… I was a bit confused about this and would appreciate some advise on this.

Regards,
Alim

The .netlify/functions and .netlify/functions-serve are used internally by Netlify CLI, the former is the path used to access the functions (this path you can change using redirects such as that configured in the netlify.toml which is correct.)

The source code for the functions in your project should not exist in the .netlify/functions directory (Netlify CLI will create this path.) Create a netlify/functions path at the root of the project for automatic detection. Alternatively (as per the netlify.toml above) use another path (e.g. functions), adding the directory configuration.

netlify dev isn’t a replacement for npm run dev per se. It is used to test the site as it would work on Netilfy, with redirects, functions, etc. A dev script (from the project package.json) likely will run the framework (Vue, React, etc.) in development mode, but functions and the like won’t work with it.

1 Like

Thanks for the clarification @coelmay … the functions are working fine now… and I guess I’ll close this ticket. However I’d appreciate if you could just confirm if my observation is accurate…

My live site and my site viewed locally when I run npm run dev are exactly the same… except that it doesn’t run the serverless functions… however my localhost site when launched using netlify dev does run the serverless functions but there are things that seem to be missing… for example I have updated a field on my forms where I am using the intlTelInput to display the flags and the international telephone codes which is visible on the live site and on the localhost when I test with npm run dev… however it’s missing when I run netlify dev…

Similarly there’s a route /voted which runs a serverless function /api/getUser and it works well only but on the netlify dev localhost site it seems to show an older version… I assumed it was a cache issue but even on an incognito window I can’t seem to get it to show…

Do let me know if it’s something that you’d be aware of or I just need to keep watching and figure if there’s something I am doing wrong… i’ve seriously checked a lot but maybe not everything…

Thanks again for your help… have a lovely day…:-)…

Regards,
Alim

It is impossible (for me) to say why things do not work as intended locally (per your testing/observation) without the ability to test it myself.

1 Like

I agree…:-)… it was just to know if you’ve encountered a similar situation with others and if you saw a pattern…:-)… anyways I’ll try and explore it… thanks again…

Thanks for the clear explanation, @coelmay! @alimbolar, glad you are on the right path now!

1 Like