Sling Academy
Home/Node.js/How to Set Up Firebase in Node.js (with TypeScript)

How to Set Up Firebase in Node.js (with TypeScript)

Last updated: January 21, 2024

Overview

Firebase is a comprehensive app development platform that comes with a suite of tools and services to help you develop high-quality apps, grow your user base, and earn more profit. Its services are hosted in the cloud and scale with ease, don’t require managing any servers, and remain accessible via easy-to-use APIs. Integrating Firebase with Node.js and TypeScript can seem daunting, but in this tutorial, we’ll step through the process together.

Prerequisites

Setting up a Node.js TypeScript Project

Let’s initiate a new Node.js project with TypeScript. Open your terminal and follow these steps:

mkdir my-firebase-app
 cd my-firebase-app
 npm init -y
 npm install typescript ts-node @types/node --save-dev
 npx tsc --init

This will create a basic project structure with the necessary TypeScript configurations. Make sure your ‘tsconfig.json’ file includes the following options for Node.js:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "ES2019",
    "moduleResolution": "node",
    "outDir": "./dist",
    "noImplicitAny": true,
    "strict": true
  },
  "include": ["./src/**/*"]
}

Create a ‘src’ directory where your TypeScript source files will reside:

mkdir src
echo console.log('Hello Firebase and TypeScript'); > src/index.ts

Installing Firebase SDK

To work with Firebase in your project, you will need to install the Firebase SDK and the types for Firebase:

npm install firebase-admin --save
 npm install @types/firebase-admin --save-dev

Initializing Firebase in Your Project

Before you begin, you need to generate a private key file for your Firebase project. In the Firebase console, go to your project’s settings, then the Service accounts tab, and generate a new private key.

Once you have the private key, initialise Firebase in your ‘src/index.ts’ file:

import * as admin from 'firebase-admin';

const serviceAccount = require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

console.log('Firebase Admin Initialized');

Replace the ‘path/to/serviceAccountKey.json’ with the actual path to the JSON file you downloaded from Firebase.

Using Firebase Services

With Firebase initialized, it’s time to dive into using its services. Here’s an example that demonstrates how to work with Firebase Authentication:

async function createUser(email: string, password: string) {
  try {
    const userRecord = await admin.auth().createUser({
      email: email,
      emailVerified: false,
      password: password,
      disabled: false
    });
    console.log('Successfully created new user:', userRecord.uid);
    return userRecord;
  }
  catch (error) {
    console.error('Error creating new user:', error);
    throw error;
  }
}

// Usage:
createUser('[email protected]', 'password123');

Similarly, here’s how to interact with Firestore, Firebase’s NoSQL cloud database:

const db = admin.firestore();

async function addData(collection: string, documentId: string, data: Object) {
  const docRef = db.collection(collection).doc(documentId);
  await docRef.set(data);
  console.log(`Document written at ID: ${documentId}`);
}

// Usage:
addData('users', 'new-user-id', { name: 'Alice', age: 25 });

Running Your TypeScript App

Have your ‘package.json’ have a script to transpile and run your TypeScript app:

{
  "scripts": {
    "start": "tsc && node ./dist/index.js"
  }
}

To run your app, execute the following:

npm start

And there you have it. You’ve successfully set up Firebase in a Node.js application using TypeScript. With Firebase’s suite of features and TypeScript’s robust typing, you can build applications that are both powerful and easy to maintain.

Error Handling and Best Practices

Here are some tips on error handling and other best practices while working with Firebase in TypeScript:

  • Always handle promises properly. Use async/await or .then() and .catch() methods.
  • Secure your Firebase keys. Never commit private keys to version control.
  • Regularly review your Firebase rules. Make sure they are up-to-date with your security requirements.
  • Type your responses and requests. Take advantage of TypeScript’s typing system.
  • Keep your functions small and focused. Each function should do one thing very well.
  • Write unit tests for your functions using frameworks like Mocha or Jest.

Following these instructions and tips will help you craft an efficient and secure application using Firebase and TypeScript. For further reference, consult the Firebase documentation and the TypeScript handbook.

Next Article: Using Firebase Auth in Node.js: The Complete Guide

Previous Article: Node.js: How to Programmatically Generate CAPTCHA (3 ways)

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates