Created
February 12, 2024 14:20
-
-
Save thewisenerd/0decd0da9b6a4ff8ec15afad8b1a8c80 to your computer and use it in GitHub Desktop.
hello process.env
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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