karmuz icon

How to handle env in Next.js

How to handle env in Next.js

Do you ever run next app from docker-compose, but when you pass the env from compose the next app didn’t receive it?

The problem

Before Next.13

Before next 13, there’s 2 version env.. build-time and run-time variable. by default env is will be generated in build time. that’s why you either need to provide the env at dockerbuild (so it will be generated at build time) or you can use run-time variable.

After Next.13

At Next.13 run-time variable is deprecated, so you can’t use it anymore.

runtime variable is deprecated

so, In order take the env from docker-compose you need to use Server Components.

Another problem in Next.13

if use server components, what we can do if our page need client service?

example:

1const fetchData = (deps) =>{
2  //fetch data
3  fetch(process.env.BASE_URL+deps);
4}
5
6useEffect(()=>{
7  fetchData(deps);
8},[deps])

we need to use “use client” in this page because we are using useEffect which only run in client side.

to take env from docker compose, you need to make sure fetching is doing in server side.

  • wrap the component with server page, put fetch function there, and pass the fetch function as a props
1//server page
2"use server"
3
4function Page(){
5  const fetchData = async (deps) => {  
6    //fetch data
7  }
8  
9  return <ClientComponent fetchData={fetchData}
10}
1//client page
2"use client"
3
4export default function ClientComponent({fetchData:fetchDataFromServer}){  
5
6  useEffect(()=>{  
7    const fetchData = async (deps) => {   
8      const data = await fetchDataFromServer(deps);
9      console.log(data)
10    }
11    fetchData(deps);
12  },[deps])
13
14// rest of the function
15}
16
  • or, you can separate the fetch into 1 action files
1// app/actions.js
2"use server"
3
4export const fetchData = async (deps) => {  
5  //fetch data
6}

for more further information, you can check this page

env
javascript
next