Skip to content

Instantly share code, notes, and snippets.

@haris-aqeel
Last active September 17, 2023 16:01
Show Gist options
  • Save haris-aqeel/aecad357dda1a4ceab938233760b9631 to your computer and use it in GitHub Desktop.
Save haris-aqeel/aecad357dda1a4ceab938233760b9631 to your computer and use it in GitHub Desktop.
// Purpose: Configure Firebase rewrite rules for Next.js static routing.
// This script is intended for statically generated Next.js projects (built with 'next build' and 'next export').
// Inspired by the discussion at: https://github.com/firebase/firebase-js-sdk/discussions/4980
import fsPromises from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
async function main() {
const args = process.argv.slice(2); // Get command-line arguments, excluding 'node' and script name
if (args.length !== 2) {
console.error('Usage: node script.js <routeManifestFilePath> <firebaseJsonFilePath>');
return;
}
const routeManifestFilePath = args[0];
const firebaseJsonFilePath = args[1];
console.info(`Using route manifest file: ${routeManifestFilePath}`);
console.info(`Using Firebase JSON file: ${firebaseJsonFilePath}`);
try {
// Read route manifest file
const routeManifestTxt = await fsPromises.readFile(routeManifestFilePath, 'utf8');
const routeManifest = JSON.parse(routeManifestTxt);
// Read Firebase configuration file
const firebaseJsonTxt = await fsPromises.readFile(firebaseJsonFilePath, 'utf8');
const firebaseJson = JSON.parse(firebaseJsonTxt);
const modifiedRoutes = routeManifest.dynamicRoutes.map(({
page,
regex,
}) => {
const destination = `${page}/index.html`;
return {
destination,
regex,
};
});
firebaseJson.hosting.rewrites = modifiedRoutes;
const firebaseJsonModTxt = JSON.stringify(firebaseJson, null, 2);
await fsProm.writeFile(firebaseJsonPath, firebaseJsonModTxt, 'utf8');
} catch (error) {
console.error('An error occurred:', error.message);
}
}
module.exports = {
images: {
loader: 'akamai',
domains: ['firebasestorage.googleapis.com'],
path: '',
},
trailingSlash: true,
};
{
"scripts": {
"dev": "next dev",
"build": "next build",
"export": "next export",
"gen-firebase-rewrites": "node script.js /path/to/routes-manifest.json /path/to/firebase.json",
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment