I was trying to do this in Nuxt for some firebase cloud messaging, and I adapted @shriek's answer above to do what I needed.
First create a file called swEnvbuild.js in root directory, as per below:
require('dotenv').config(); // make sure you have '.env' file in pwd
const fs = require('fs');
fs.writeFileSync('./public/swenv.js',
`
const process = {
env: {
FB_API_KEY: '${process.env.FIREBASE_API_KEY}',
FB_AUTHDOMAIN: '${process.env.FIREBASE_AUTHDOMAIN}',
FB_PROJECTID: '${process.env.FIREBASE_PROJECTID}',
FB_STORAGEBUCKET: '${process.env.FIREBASE_STORAGEBUCKET}',
FB_MESSAGINGSENDERID: '${process.env.FIREBASE_MESSAGINGSENDERID}',
FB_APPID: '${process.env.FIREBASE_APPID}',
FB_MEASUREMENTID: '${process.env.FIREBASE_MEASUREMENTID}',
FB_PUSHNOTETOKEN: '${process.env.FIREBASE_PUSHNOTETOKEN}'
}
}
`);
Then, update your service worker file with:
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js');
importScripts('swenv.js'); // this file should have all the vars declared, allowing you to use process.env.ANY_KEY_YOU_DEFINED
firebase.initializeApp({
apiKey: process.env.FB_API_KEY,
authDomain: process.env.FB_AUTHDOMAIN,
projectId: process.env.FB_PROJECTID,
storageBucket: process.env.FB_STORAGEBUCKET,
messagingSenderId: process.env.FB_MESSAGINGSENDERID,
appId: process.env.FB_APPID,
measurementId: process.env.FB_MEASUREMENTID
});
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js', { type: 'module', scope: '__' })
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
const isSupported = firebase.messaging.isSupported();
if (isSupported) {
const messaging = firebase.messaging();
messaging.onBackgroundMessage(({ notification: { title, body, image } }) => {
self.registration.showNotification(title, { body, icon: image || '/assets/icons/icon-72x72.png' });
});
}
Finally, update your package.json to build the required file
// add 'node swEnvBuild.js' to build and start script
"scripts": {
"build": "nuxt build && node swEnvBuild.js",
"dev": "node swEnvBuild.js && nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"start": "node .output/server/index.
}
That did it for me