Created
November 6, 2024 12:01
-
-
Save emnopal/bebb7f7826d04dc4583331c4e42e398f to your computer and use it in GitHub Desktop.
spreading env to across next app (since .env which is defined while running `next dev` is not same with `next start`)
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
| "use client"; | |
| import { createContext, useContext, useEffect, useState } from "react"; | |
| import { getEnv } from "./env"; | |
| const EnvContext = createContext({}); | |
| type envType = Record<string, string | undefined>; | |
| export const EnvProvider = ({ | |
| children, | |
| }: Readonly<{ | |
| children: React.ReactNode; | |
| }>) => { | |
| const [env, setEnv] = useState<envType>({}); | |
| useEffect(() => { | |
| getEnv().then((env) => { | |
| setEnv(env); | |
| }); | |
| }, []); | |
| return <EnvContext.Provider value={env}>{children}</EnvContext.Provider>; | |
| }; | |
| export const useEnv = () => { | |
| return useContext<envType>(EnvContext); | |
| }; |
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
| "use server"; | |
| export const getEnv = async () => ({ | |
| EXAMPLE_ENV: process.env.EXAMPLE_ENV, | |
| // notes: do not put sensitive information such as api key or something secret here | |
| // since it will expose to client side | |
| }); |
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
| 'use client'; | |
| import { ReactNode } from 'react'; | |
| import { EnvProvider } from '../utils/env/envProvider'; | |
| export default function RootLayout({ children }: { children: ReactNode }) { | |
| return ( | |
| <html lang="en"> | |
| <body> | |
| <EnvProvider> | |
| <link rel="icon" href="/icon.png" sizes="any" /> | |
| {children} | |
| </EnvProvider> | |
| </body> | |
| </html> | |
| ); | |
| } |
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
| "use client"; | |
| import { useEnv } from '../../../utils/env/envProvider'; | |
| // ENV Usage on client side | |
| export default function Example() { | |
| const env = useEnv() | |
| return ( | |
| <div> | |
| {env.EXAMPLE_ENV ?? ""} | |
| </div> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment