2

I'm following This tutorial, trying to deploy some functions to Firebase, and I can successfully deploy them to my project id. When accessing the following function on the provided URL, I get the error: could not handle the request

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup 
triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database. 
const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.date = functions.https.onRequest((req, res) => {
let format = req.query.format;
const date = moment().format();
res.status(200).json({ date: date});
})

My Firebase console logs this on execution:

ReferenceError: moment is not defined
at exports.date.functions.https.onRequest (/user_code/index.js:10:24)
at cloudFunction (/user_code/node_modules/firebase-
functions/lib/providers/https.js:26:41)
at /var/tmp/worker/worker.js:635:7
at /var/tmp/worker/worker.js:619:9
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)

My package.json in my functions folder has "moment": "^2.19.1" under dependencies.

What am I doing wrong? How do I define moment?

1 Answer 1

6

Having moment.js defined in your package.json only means that it'll be installed in the environment where your code runs. To have it available in your code, you need to import the moment library:

const functions = require('firebase-functions');
const moment = require('moment');

const admin = require ('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.date = functions.https.onRequest((req, res) => {
  let format = req.query.format;
  const date = moment().format();
  res.status(200).json({ date: date});
})

Also see the moment.js docs for using it in node.js.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.