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

Yuuta Moriyama
  • 449
  • 1
  • 4
  • 10

7 Answers7

28

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';
samthecodingman
  • 23,122
  • 4
  • 30
  • 54
Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85
15

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)
});
frfernandezdev
  • 383
  • 4
  • 10
10

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),
})
chantey
  • 4,252
  • 1
  • 35
  • 40
  • 4
    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. – Nick Sweeting Dec 15 '20 at 12:19
  • 1
    @NickSweeting Better late than never, but it will be `firebase.firestore.Firestore` (from the import) or `FirebaseFirestore.Firestore` (the global type). – samthecodingman Jul 07 '21 at 18:02
3

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

Llanas
  • 41
  • 2
2

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.
})
PQrux
  • 153
  • 1
  • 6
  • 2
    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()`. – samthecodingman Jul 07 '21 at 17:56
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;
Vigneshwaran
  • 41
  • 1
  • 6
  • 2
    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](/help/how-to-answer). – Community Nov 03 '22 at 08:58
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();
  • 1
    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 [answer]. – ChrisGPT was on strike Aug 15 '22 at 00:26
  • This answer was reviewed in the [Low Quality Queue](https://stackoverflow.com/help/review-low-quality). Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-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 Review](https://stackoverflow.com/review/low-quality-posts/32484482) – Trenton McKinney Aug 15 '22 at 00:52