Using instrumentation to add NEXT_PUBLIC env variables in js file in the public directory
Unanswered
nevz posted this in #help-forum
nevzOP
Currently I'm trying to inject my environment variables in a service worker file inside of the public directory, I've done a lot of things but all of them ended up with having
So I've tried using instrumentation, it works but is this a good use case? Anything better or is this good enough?
undefined as the value (Docker is a pain)So I've tried using instrumentation, it works but is this a good use case? Anything better or is this good enough?
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
const path = await import('node:path');
const fs = await import('node:fs/promises');
const CONFIG = {
someKey: process.env.NEXT_PUBLIC_SOME_KEY,
someOtherKey: process.env.NEXT_PUBLIC_SOME_OTHER_KEY
};
await fs.writeFile(
path.join(__dirname, '..', '..', 'public', 'sw.js'),
`
const CONFIG = ${JSON.stringify(CONFIG)}
`,
);
}
}2 Replies
Burmese
kind of a hack... but if it works 🤷♂️
another option would be adding a webpack plugin in your next.config file to inject it. Webpack is a whole giant rabbithole to get sucked into though and the docs are not great.