2

I am hoping to use Google Cloud Functions to interact with the Notion API. I'm getting started by lifting the first example from their API doc and putting it into a CF (see below). However I'm getting the following error log:

Detailed stack trace: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /workspace/index.js

I was receiving a similar message when trying to run the Notion API locally, but was able to get around that by changing import { Client } from "@notionhq/client" to import notion from "@notionhq/client"; const Client = notion. That fix does not work in the cloud function for some reason.

I have also read in other SO answers that I need to change the type in package.json to module, but I have already done so and the issue still persists.

index.js


import { Client } from "@notionhq/client"

exports.notionBot = (req, res) => {
  let message = req.query.message || req.body.message || 'Testing the notion API with Cloud Functions!';

  const notion = new Client({ auth: process.env.NOTION_KEY })

  const databaseId = process.env.NOTION_DATABASE_ID

  async function addItem(text) {
    try {
      await notion.request({
        path: "pages",
        method: "POST",
        body: {
          parent: { database_id: databaseId },
          properties: {
            title: { 
              title:[
                {
                  "text": {
                    "content": text
                  }
                }
              ]
            }
          }
        },
      })
      console.log("Success! Entry added.")
    } catch (error) {
      console.error(error.body)
    }
  }

  addItem("Yurts in Big Sur, California")

  res.status(200).send(message);
};

package.json

{
  "name": "notion-example",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "@notionhq/client": "^0.1.9",
    "esm": "^3.2.25"
  }
}
user12457151
  • 853
  • 2
  • 12
  • 25

2 Answers2

1

Google Cloud Functions does not support ES modules yet. See "Note" under https://cloud.google.com/functions/docs/migrating/nodejs-runtimes#nodejs-14-changes .

You need to either rewrite your functions as CommonJS (i.e. use require instead of import) or use tools like Babel to transpile your code into CommonJS.

(Note that support for ES module is coming soon: https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/233)

Daniel L
  • 450
  • 3
  • 6
  • Google Cloud Functions just announced support for ES modules https://medium.com/google-cloud/es-modules-in-cloud-functions-f5be1676c8b5 – Daniel L Aug 17 '21 at 04:56
1

As of Firebase Tools v9.15.0, you can now use ES Modules in Cloud Functions.

https://github.com/firebase/firebase-tools/releases/tag/v9.15.0

samthecodingman
  • 23,122
  • 4
  • 30
  • 54