Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

I create a project that uses React + Firebase + Lambda Functions.

I have Firebase code on the front end and I needed a bit of back-end to handle some events.

As I use Netlify to deploy my app, I have access to Amazon Lambda Functions with netlify-lambda. (https://www.netlify.com/docs/functions/)

Usually, everything just works (MailChimp API, snipcart API etc ...)

But I can not get Firebase working.

I created a service account with the rights to write and read.

Here the code of my lambda function: (Just a test to try to see the users section of the database.)

import firebaseAdmin from 'firebase-admin'

const serviceAccount = require('../utils/FirebaseServiceAccountKey.json')

export function handler (event, context, callback) {

  firebaseAdmin.initializeApp({

    credential: firebaseAdmin.credential.cert(serviceAccount),

    databaseURL: 'https://sample-3615.firebaseio.com'

  })

  const db = firebaseAdmin.database()

  const ref = db.ref('/users')

  let users = {}

  ref.once('value', function (snapshot) {

    console.log(snapshot.val())

    users = snapshot.val()

  })

  callback(null, {

    statusCode: 200,

    body: JSON.stringify({ users })

  })

}

It returns me : TypeError: rtdb.initStandalone is not a function.

I also have many Warning like this: Module not found: Error: Can not resolve 'memcpy' and for other packages too.

My call to the function in a Component:

handleClick = (e) => {

    e.preventDefault()

    this.setState({loading: true})

    fetch('/.netlify/functions/score')

      .then(res => res.json())

      .then(json => console.log(json.users))

      .then(() => this.setState({loading: false}))

  }

I'm not sure where the problem comes from. Webpack?

1 Answer

0 votes
by (44.4k points)

I have not been able to run the SDK with AWS Lambda from Netlify.

To use Firebase from Netlify Lambda Functions I am going through the REST API with admin privileges.

From REST API with admin privileges, we can access Firebase from Netlify Lambda Functions 

https://firebase.google.com/docs/reference/rest/database/

It works perfectly like that.

import { google } from 'googleapis'

import fetch from 'node-fetch'

const serviceAccount = require('../utils/FirebaseServiceAccountKey.json')

const scopes = [

  'https://www.googleapis.com/auth/userinfo.email',

  'https://www.googleapis.com/auth/firebase.database'

]

// Authenticate a JWT client with the service account.

const jwtClient = new google.auth.JWT(

  serviceAccount.client_email,

  null,

  serviceAccount.private_key,

  scopes

)

export function handler (event, context, callback) {

  const res = JSON.parse(event.body)

  // Use the JWT client to generate an access token.

  jwtClient.authorize(async function (error, tokens) {

    if (error) {

      console.log('Error making request to generate access token:', error)

    } else if (tokens.access_token === null) {

      console.log('Provided service account does not have permission to generate access tokens')

    } else {

      const accessToken = tokens.access_token

      const score = await fetch(`https://example-3615.firebaseio.com/scores/${res.uid}/score.json`)

        .then(data => data.json())

        .then(score => score + res.score)

      fetch(`https://example-3615.firebaseio.com/scores/${res.uid}.json?access_token=${accessToken}`, {

        body: JSON.stringify({ score, displayName: res.user.displayName, photoURL: res.user.photoURL }),

        headers: {

          'Content-Type': 'application/x-www-form-urlencoded'

        },

        method: 'PATCH'

      })

        .then(() => {

          callback(null, {

            statusCode: 200,

            body: 'Score +1'

          })

        })

    }

  })

}

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
2 answers
asked Oct 18, 2019 in Web Technology by Sammy (47.6k points)

Browse Categories

...