Problems with running scheduled functions

Site name: missoma-monitoring

I have a scheduled function that fetches some data from an API and then pushes it to a metaobject in Shopify. This all works perfectly when running locally, but as soon as I push to Netlify and try to invoke the function, I get the following error:

Mar 17, 09:01:46 AM: INIT_START Runtime Version: nodejs:16.v12	Runtime Version ARN: arn:aws:lambda:us-east-1::runtime:734d712d91ebc245bd01c52ae85b4025a7885efd1b8c87c0ce49f3e47d2116a4
Mar 17, 09:01:46 AM: 1309d816 INFO   [request] /.netlify/functions/next_api_globalecoefficientuk
Mar 17, 09:01:46 AM: 1309d816 ERROR  TypeError: Cannot read properties of undefined (reading 'headers')
    at Object.apiResolver (/var/task/nextPage/chunks/458.js:2946:55)
    at Module.<anonymous> (/var/task/nextPage/chunks/458.js:123:30)
Mar 17, 09:01:46 AM: 1309d816 ERROR  TypeError: Cannot read properties of undefined (reading 'headers')
    at Object.apiResolver (/var/task/nextPage/chunks/458.js:2946:55)
    at Module.<anonymous> (/var/task/nextPage/chunks/458.js:123:30)
Mar 17, 09:01:46 AM: 1309d816 ERROR  Unhandled Promise Rejection 	{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: Cannot read properties of undefined (reading 'headers')","reason":{"errorType":"TypeError","errorMessage":"Cannot read properties of undefined (reading 'headers')","stack":["TypeError: Cannot read properties of undefined (reading 'headers')","    at Object.apiResolver (/var/task/nextPage/chunks/458.js:2946:55)","    at Module.<anonymous> (/var/task/nextPage/chunks/458.js:123:30)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError: Cannot read properties of undefined (reading 'headers')","    at process.<anonymous> (file:///var/runtime/index.mjs:1188:17)","    at process.emit (node:events:513:28)","    at emit (node:internal/process/promises:140:20)","    at processPromiseRejections (node:internal/process/promises:274:27)","    at processTicksAndRejections (node:internal/process/task_queues:97:32)"]}
Mar 17, 09:01:46 AM: Unknown application error occurred
Runtime.Unknown
Mar 17, 09:01:46 AM: 1309d816 Duration: 15.45 ms	Memory Usage: 71 MB	Init Duration: 276.12 ms
Mar 17, 09:01:46 AM: INIT_START Runtime Version: nodejs:16.v12	Runtime Version ARN: arn:aws:lambda:us-east-1::runtime:734d712d91ebc245bd01c52ae85b4025a7885efd1b8c87c0ce49f3e47d2116a4

I have gone through the code, rewritten it, deleted it, written it again, cried, considered my life choices, rewritten it again and still no luck. I cannot see what the problem is.

Here is the current version of the code:

export default (_req, _res) => {
  (async () => {
        const rawResponse = await fetch('MY API URL', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({a: 1, b: 2})
        });
        const content = await rawResponse.json();

        console.log(content);

        const graphql = JSON.stringify({
          query:
            "mutation metaobjectUpdate($id: ID!, $metaobject: MetaobjectUpdateInput!) {\n  metaobjectUpdate(id: $id, metaobject: $metaobject) {\n    metaobject {\n        id\n        fields {\n            value\n        }\n    }\n    userErrors {\n      field\n      message\n    }\n  }\n}",
          variables: {
            id: "MY SHOPIFY GID",
            metaobject: {
              fields: [{ key: "rates", value: JSON.stringify(content) }],
              handle: "MY HANDLE",
            },
          },
        });

        const requestOptions = {
          method: "POST",
          headers: {
            'X-Shopify-Access-Token': 'MY TOKEN',
            'Content-Type': 'application/json'
          },
          body: graphql,
          redirect: "follow",
        };

        fetch("MY API URL", requestOptions)

      })();

      return {
        statusCode: 200,
        body: JSON.stringify({ message: "Coeffcients have been updated!" }),
      };
}

export const config = {
  type: "experimental-background",
  schedule: "0 3 * * *",
};

I’ve tried using other methods instead of just having two fetch requests like using .then() and having a new Promise() to handle the second part of updating Shopify but it didn’t make a difference.

As I mentioned above, this all works perfectly when I run it locally, it’s just when it’s built in Netlify that it fails. I’ve been through Netlify support but unfortunately, they couldn’t help resolve the issue and suggested I try here.

Thanks!

Hey @66c0de6e26e43ba1d0b1 what version of next are you using?

If you could share the repo either publicly or privately, I’d be more than happy to take a look at it.

Hey @kylesloper, I’m using v12.0.2

The repo contains some info that I can’t really share as this is an internal tool and has some sensitive information on it, but I’m happy to explain anything you need to know.

Thanks!

Hi @66c0de6e26e43ba1d0b1,

Since you’re using fetch are you using node-fetch or the global function available in Node.js? Based on your code, I’m assuming it’s the latter, but you’re using Node 16 for your Functions. Global fetch was available as stable only in Node 18, I believe. Could you try upgrading to Node 18 to see if it works: Optional configuration for functions | Netlify Docs

If it still doesn’t, we would really need a minimal version of your repo or some code that reproduces this issue to be able to test and debug it.

@hrishikesh thanks for your reply. I’m using global fetch, so I updated to v18 as per the documentation but I’m still getting the error. Is there a way I can privately share the repo with you? Thanks

You can send any of us the repo via a private message. If it contains confidential information make sure to send us a redacted version

@kylesloper How can I send it to you privately?

you can send a private message on this forum

I don’t seem to have that option, ping me you git handle?

The issue is still unresolved if anyone is able to help.

Thanks!

I’d suggest you make a public copy of your repo without any sensitive code in it to show us instead :slight_smile: I can’t see whatever you might have shared with someone else; sharing with me won’t work since I don’t read DM’s on here.

I have found another solution using PowerAutomate.

Thanks for letting us know!