Skip to content

Instantly share code, notes, and snippets.

@thewisenerd
Created February 12, 2024 14:20
Show Gist options
  • Save thewisenerd/0decd0da9b6a4ff8ec15afad8b1a8c80 to your computer and use it in GitHub Desktop.
Save thewisenerd/0decd0da9b6a4ff8ec15afad8b1a8c80 to your computer and use it in GitHub Desktop.
hello process.env
// src/lib/env.ts
export function env(envKey: string): string | undefined {
if (typeof window === 'undefined') {
console.error("[__NEXT_PUBLIC__] env() is not expected to be invoked on the server. this is a recoverable bug.");
return process.env[envKey];
}
if (!('__NEXT_PUBLIC__' in window)) {
console.error("[__NEXT_PUBLIC__] window.__NEXT_PUBLIC__ is not defined. this is a bug.");
return undefined;
}
return (window as any)['__NEXT_PUBLIC__'][envKey];
}
// src/app/api/env.js/route.ts
export const dynamic = 'force-dynamic' // defaults to auto
export async function GET(req: Request) {
const response: Record<string, string | undefined> = {};
for (let envKey in process.env) {
if (envKey.startsWith('NEXT_PUBLIC_')) {
response[envKey] = process.env[envKey];
}
}
return new Response(`window.__NEXT_PUBLIC__=` + JSON.stringify(response) + ';', {
headers: {
'Content-Type': 'text/javascript'
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment