Skip to main content

Handling Proxy Issues with Firebase in Node.js

·314 words·2 mins
Sebastian Scheibe
Author
Sebastian Scheibe
Table of Contents

Introduction
#

Firebase is widely used for authentication, database management, and other server-side operations in Node.js applications. However, when operating behind a corporate proxy or firewall, you might encounter connection issues that hinder communication with Firebase services. In this article, we will explore how to configure Firebase behind a proxy using the proxy-agent package.

Proxy with Firebase
#

Here’s an example of how your Firebase initialization code might look:

The service key is imported, and we use that to initialize the Firebase SDK.

import admin from "firebase-admin";
import path from "node:path";

const FIREBASE_JSON_KEY_LOCATION = env.FIREBASE_JSON_KEY_LOCATION

const serviceAccountPath = path.isAbsolute(FIREBASE_JSON_KEY_LOCATION)
      ? FIREBASE_JSON_KEY_LOCATION 
      : path.join(process.cwd(), FIREBASE_JSON_KEY_LOCATION);

const serviceAccount = require(serviceAccountPath);

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

Install Proxy-Agent
#

To be able to use the proxy variables, like HTTP_PROXY and HTTPS_PROXY, we can use the proxy-agent package which will automatically parse those variables and give us an agent.

Let’s install proxy-agent

npm install proxy-agent

Integrate Proxy-Agent
#

To ensure the proxy is used correctly, we need to pass the ProxyAgent instance both in the httpAgent for Firebase’s general requests and in the credential object for authentication calls.

The ProxyAgent must be included in both the httpAgent and credential parameters to ensure that all outgoing requests, including authentication requests with Firebase, are routed through the proxy.

import admin from "firebase-admin";
import path from "node:path";
import { ProxyAgent } from 'proxy-agent';

// The ProxyAgent automatically detects and applies the correct proxy settings 
// based on the HTTP_PROXY and HTTPS_PROXY environment variables.
const agent = new ProxyAgent();

const FIREBASE_JSON_KEY_LOCATION = env.FIREBASE_JSON_KEY_LOCATION

const serviceAccountPath = path.isAbsolute(FIREBASE_JSON_KEY_LOCATION)
      ? FIREBASE_JSON_KEY_LOCATION 
      : path.join(process.cwd(), FIREBASE_JSON_KEY_LOCATION);

const serviceAccount = require(serviceAccountPath);

admin.initializeApp({
    projectId: serviceAccount.project_id,
    credential: admin.credential.cert(serviceAccount, agent),
    httpAgent: agent
});

Conclusion
#

By using proxy-agent, you ensure that Firebase requests can pass through proxies without issues, which is particularly useful in corporate environments where proxy restrictions are common.

Resources
#

Firebase NodeJS SDK

Proxy-Agent NPM page