Skip to content

Instantly share code, notes, and snippets.

Last active March 28, 2023 16:37
Show Gist options
  • Save puf/e00c34dd82b35c56e91adbc3a9b1c412 to your computer and use it in GitHub Desktop.
Save puf/e00c34dd82b35c56e91adbc3a9b1c412 to your computer and use it in GitHub Desktop.
Firebase Hosting Deploy Single File

This script may no longer work. Have a look at its (more official) replacement:

Firebase Hosting Deploy Single File

This utility script deploy a single local file to an existing Firebase Hosting site. Other files that are already deployed are left unmodified.

The difference with firebase deploy is that this script does not require you to have a local snapshot of all hosted files, you just need the one file that you want to add/update.



node deployFile.js <site_name> <file_to_deploy> [commit]

Installation / Example

To use this script, you must have a signed-in installation of the Firebase CLI.

git clone firebase-hosting-deploy-file
cd firebase-hosting-deploy-file
npm install

# perform a dry run, make sure you're not doing something you'll regret
node deployFile.js contentsite /index.html

# do the deletion for real
node deployFile.js contentsite /index.html commit
const fs = require("fs");
const path = require("path");
const zlib = require("zlib");const crypto = require('crypto');
const request = require("request");
const { getGlobalDefaultAccount } = require('firebase-tools/lib/auth'); // see
const api = require('firebase-tools/lib/api');
const isDryRun = process.argv[4] !== "commit";
if (!process.argv[2] || !process.argv[3]) {
ERROR: Must supply a site name and file to deploy. Usage:
node deployFile.js <site_name> <file_to_deploy> [commit]`);
const site = process.argv[2];
const file = process.argv[3];
requireAuth(getGlobalDefaultAccount(), ['']).then(async () => {
try {
// Steps in this script:
// 1. Determine version of the latest release
// 2. Get list of files in that version
// 3. Determine the hash of our local file
// 4. Create a new version
// 5. Send list of files from previous version, with our own local file in there too
// 6. Upload our local file if the Hosting server requests it
// 7. Finalize our new version
// 8. Create a release on this new version
// Determine the latest release
console.log("Determining latest release...")
var response = await api.request('GET', `/v1beta1/sites/${site}/releases`, { auth: true, origin: api.hostingApiOrigin });
let releases = response.body.releases;
releases.forEach((release) => { console.log(/*, */release.version.status, release.version.createTime, release.version.fileCount,; })
let latestVersion = releases[0];
// Get the files in the latest version
console.log("Getting files in latest version...")
response = await api.request('GET', `/v1beta1/${latestVersion}/files`, { auth: true, origin: api.hostingApiOrigin });
var files = {};
response.body.files.forEach(file => {
files[file.path] = file.hash;
// prep our own file that we're uploading
const hasher = crypto.createHash("sha256");
const gzipper = zlib.createGzip({ level: 9 });
var zipstream = fs.createReadStream(process.cwd()+file).pipe(gzipper);
files[file] = await new Promise(function(resolve, reject) {
zipstream.on("end", function() {
zipstream.on("error", reject);
// Create a new version
console.log("Creating new version...")
response = await api.request('POST', `/v1beta1/sites/${site}/versions`, { auth: true, origin: api.hostingApiOrigin });
let version =;
// Send file info for the new version to the server, to hear what we need to upload
console.log("Sending file listing for new version...")
response = await api.request('POST', `/v1beta1/${version}:populateFiles`, {
auth: true,
origin: api.hostingApiOrigin,
data: { files: files }
let requiredHashes = response.body.uploadRequiredHashes;
let uploadUrl = response.body.uploadUrl;
if (requiredHashes && requiredHashes.indexOf(files[file]) >= 0) {
console.log(`Uploading ${file}...`)
let reqOpts = await api.addRequestHeaders({
url: uploadUrl +"/"+ files[file],
await new Promise(function(resolve, reject) {
fs.createReadStream(process.cwd()+file).pipe(zlib.createGzip({ level: 9 })).pipe(, function(err, res) {
if (err) {
return reject(err);
} else if (res.statusCode !== 200) {
return reject(new Error("Unexpected error while uploading file."));
if (!isDryRun) {
console.log("Finalizing new version...");
response = await api.request('PATCH', `/v1beta1/${version}?updateMask=status`, {
origin: api.hostingApiOrigin,
auth: true,
data: { status: "FINALIZED" },
console.log("Releasing new version...");
response = await api.request('POST', `/v1beta1/sites/${site}/releases?version_name=${version}`, {
auth: true,
origin: api.hostingApiOrigin,
data: { message: "Deployed from test.js" || null },
else {
console.log("Dry run only.")
// Delete the version we just created, just to be nice
console.log("Deleting new version...")
response = await api.request('DELETE', `/v1beta1/${version}`, { auth: true, origin: api.hostingApiOrigin });
} catch (error) {
"dependencies": {
"firebase-tools": "^4.2.0"
"engines": {
"node": ">= 8.0.0"
Copy link

That's interesting David. I would've expected the new version to have the same config as the existing version, but you're saying that it doesn't?

Yep, that is exactly what I am seeing. All of our rewrites were gone after the file was uploaded and released. I would have expected the same thing as you, for the existing config to remain.

Copy link

puf commented Nov 11, 2020

Darn. I'm not sure if that's a change in behavior, because I likely never tried with a non-default config. I hope others find your comment/fix, and will merge it in if there are more reports. Thanks again!

Copy link

I am getting:

requireAuth({}, ['']).then(async () => {

TypeError: requireAuth is not a function
at Object. (C:\Dev\Repos\firebase-hosting-deploy-file\deployFile.js:21:1)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47

Any idea?

Copy link

With firebase-tools >= 9.9.0 the requireAuth function has changed and now requires an Account object passed in, it won't automatically grab one.

These changes work (I'll propose the same here as edits)

// add this new import at the top
const { getGlobalDefaultAccount } = require('firebase-tools/lib/auth');

// use the import to get the current default account (assuming that is the account you want...)
const defaultAccount = getGlobalDefaultAccount();

// now send that account in, instead of the empty object before
//requireAuth({}, [''])  // old version, no account
requireAuth(defaultAccount, [''])  // new version, works

upstream issue firebase/firebase-tools#3308

Copy link

@puf I just realized I cannot actually PR to this file, but if you look at the comment immediately above ☝️ you will see a code edit required for firebase-tools >= 9.9.0

Copy link

puf commented Apr 24, 2021

Thanks for the update Mike. 👍 I merged the changes.
Does this mean it is no longer possible to run with the user that is logged in to the Firebase CLI? Or did we already lose that ability before?

Copy link

As far as I can tell, this is just a change / new feature in firebase-tools that allows (if you use new APIs) more than one user to have stored credentials, and for you to select from them. What I did with this specific change was used the new API that gets the "global default user" (aka, what we had before) and uses that as some user has to be given to requireAuth now (it won't go find one if you don't provide one). And I think my change is backwards compatible with regards to behavior, though of course if people try to use this on firebase-tools <= 9.8.0 now it will fail.

So to be precise and less wordy: this change should continue deploying single files using the user currently logged in to the firebase CLI, same as ever (it does in my testing anyway)

Copy link

puf commented Apr 24, 2021 via email

Copy link

puf commented Aug 25, 2022

If you find this script not working for you anymore, have a look at its (more official) replacement here:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment