firebase-admin with typescript in firebase cloud functions
Asked Answered
F

8

21

I am using firebase cloud functions with javascript on cloud functions. And, I want to switch from javascript to typescript.

However I cannot use firebase-admin on typescript as following command failed.

command: npm install @types/firebase-admin --save-dev
error:  '@types/firebase-admin' is not in the npm registry.

According to this release note, it looks that firebase admin support typescript. Can somebody tell us how to use typescript with firebase-admin on cloud functions?

https://firebase.google.com/support/release-notes/admin/node#4.1.3

Fricassee answered 27/5, 2017 at 18:28 Comment(0)
E
29

You don't need to install an @types module, because firebase-admin ships with TypeScript support in the box. You should be able to use it with TypeScript just by installing firebase-admin.

import * as admin from 'firebase-admin';
Electrostatic answered 28/5, 2017 at 2:52 Comment(0)
C
20

Another option could be this way.

import * as admin from 'firebase-admin';
import * as serviceAccount from './service-account.json';

const firebaseAdmin = admin.initializeApp({
   credential: admin.credential.cert(serviceAccount as admin.ServiceAccount)
});
Christcross answered 7/8, 2021 at 3:18 Comment(0)
H
11

It seems that types are provided when imported using ES6 Modules:

  1. tsconfig.json
{
    "compilerOptions": {
        "resolveJsonModule": true,               // json imports
        "esModuleInterop": true,                 // import common modules as ES6 Modules
        "allowSyntheticDefaultImports": true,    // support typesystem compatibility
    }
}
  1. index.ts
import firebase from 'firebase-admin';
import serviceAccount from './service-account.json';

//snake_case to camelCase
const params = {
    type: serviceAccount.type,
    projectId: serviceAccount.project_id,
    privateKeyId: serviceAccount.private_key_id,
    privateKey: serviceAccount.private_key,
    clientEmail: serviceAccount.client_email,
    clientId: serviceAccount.client_id,
    authUri: serviceAccount.auth_uri,
    tokenUri: serviceAccount.token_uri,
    authProviderX509CertUrl: serviceAccount.auth_provider_x509_cert_url,
    clientC509CertUrl: serviceAccount.client_x509_cert_url
}

firebase.initializeApp({
    credential: firebase.credential.cert(params),
})
Helaina answered 16/8, 2020 at 6:53 Comment(2)
What is the type of const db = firebase.firestore()? I can't seem to find a typescript type that works for it anywhere, I've tried firebase.FirebaseFirestore and many other things to no avail.Dawes
@NickSweeting Better late than never, but it will be firebase.firestore.Firestore (from the import) or FirebaseFirestore.Firestore (the global type).Latten
Q
4

For those who are still struggling, reloading VSCode after installing firebase-admin did the work for me.

Quid answered 4/1, 2021 at 15:52 Comment(2)
ctrl+shift+p -> restart ts server may have the same effectHelaina
How is this possible? I've been struggling for hours..Razz
T
3

I know i'm late but I found another way to do this, using the answer given by Peter:

  1. tsconfig.json
{
    "compilerOptions": {
        "resolveJsonModule": true,               // json imports
        "esModuleInterop": true,                 // import common modules as ES6 Modules
        "allowSyntheticDefaultImports": true,    // support typesystem compatibility
    }
}
  1. index.ts
import firebase from 'firebase-admin';
import serviceAccount from './service-account.json';

firebase.initializeApp({
    credential: firebase.credential.cert(serviceAccount as any), //Cast as any instead of clone the JSON.
})
Trepang answered 7/7, 2021 at 17:47 Comment(1)
Using any should be discouraged, instead use as firebase.ServiceAccount. However, if using Cloud Functions, there is no need to even manually specify a service account, just call firebase.initializeApp().Latten
B
2
import { initializeApp, cert } from 'firebase-admin/app';
import { getMessaging } from 'firebase-admin/messaging';

const app: App = initializeApp(
  {
    credential: cert('./firebase.json'),
  },
  'appname',
);

class PushNotificationService {
  options = {
    priority: 'high',
    timeToLive: 60 * 60 * 24,
  };
  
  send = (userToken: any, message: any): void => {
      getMessaging(app)
      .sendToDevice(userToken, message, this.options)
      .then(response => {
        console.log('Successfully sent message:', response);
      })
      .catch(error => {
        console.log('Error sending message:', error);
      });
  };
}

export default PushNotificationService;
Brittbritta answered 31/10, 2022 at 10:2 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Wellestablished
H
0
import * as admin from 'firebase-admin';
const serviceAccount = require('./firebase.json');

if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
  });
}

export const firebaseDB = admin.firestore();
Hercules answered 14/8, 2022 at 17:38 Comment(2)
Welcome to Stack Overflow. Code is a lot more helpful when it is accompanied by an explanation. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your answer and explain how it answers the specific question being asked. See How to Answer.Mordant
This answer was reviewed in the Low Quality Queue. Here are some guidelines for How do I write a good answer?. Code only answers are not considered good answers, and are likely to be downvoted and/or deleted because they are less useful to a community of learners. It's only obvious to you. Explain what it does, and how it's different / better than existing answers. From ReviewBeverle
R
0

Dynamically import the correct serviceaccount.json file using path initialization.

import { credential } from "firebase-admin";
import { initializeApp } from "firebase-admin/app";

let env = process.env.NODE_ENV || 'staging'
if (env === 'development') env = 'staging'

export const firebaseApp = initializeApp({
  credential: credential.cert(`${__dirname}/${env}/firebase-adminsdk.json`)
})
Rettarettig answered 8/4 at 6:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.