Next.js is a popular React framework that offers a wide range of features, one of which is the ability to use environment variables. These variables are essential for protecting sensitive data and configuring your application based on the environment itβs running in. In this blog post, weβll discuss how to add and use .env variables in your Next.js app, and how to solve a common problem where .env variables are undefined or not getting the correct value.
Creating .env.local file in the root folder:
Create a .env.local file in your root.
Write any variable name you want,
E.g: .env.local:
API_URL = https://jsonplaceholder.typicode.com/posts
Now we can use this
API_URL
variable in ourapp/page.tsx
file, Below is the code and output:export default async function Home() { const res = await fetch(process.env.API_URL); const data = await res.json(); return ( <main id="home" className="flex min-h-screen flex-col items-center justify-between p-24" > <ul> {data.map((e, i) => ( <li className="my-5" key={e.userId}> {i + 1}: {e.title} </li> ))} </ul> </main> ); }
Some common problems faced at the beginning:
Not able to use .env variables on the client-side components.
Let's first create a new .env variable to test and a client component
Heading.tsx
in the app folder."use client"; export default function Heading() { return <h1 className="text-3xl">{process.env.USERNAME}</h1>; }
.env.local:
USERNAME = Yash Purohit
Error:
This is because when your Next.js application is built, it runs in a Node.js environment (server-side). However, once the JavaScript is sent to the client, it runs in a completely different environment (client-side).
Solution: To solve this, Next.js instructs us to prefix our .env variables with
NEXT_PUBLIC_[VARIABLE NAME]
Output:
/* .env.local: file */ NEXT_PUBLIC_USERNAME = Yash Purohit
/* Heading.tsx */ "use client"; export default function Heading() { return <h1 className="text-3xl">{process.env.NEXT_PUBLIC_USERNAME}</h1>; }
.env variables becoming undefined:
There might be a case when you want to store secret credentials, it can have various kinds of characters and special characters.
Now here comes the problem, Let's say we edit our
USERNAME
variable to have$
symbol in it.NextJs won't accept the string after
$
, You can see the output below.NEXT_PUBLIC_USERNAME = Jhon $tephen
-
I'm using codesandbox.io to run this demo, That's why it is displaying only Jhon. If you run this on your local server you will get some errors like
Failed to load env - Cannot read properties of undefined (reading 'split')
Solution: I found this solution and issue here:
https://github.com/vercel/next.js/discussions/35818
/* all you need to do is escape (\) the character to get recognised by nextjs.*/ NEXT_PUBLIC_USERNAME = Jhon \$tephen
You can view this sandbox at codesandbox.io/p/sandbox/nostalgic-yalow-c5..
Comment your feedback on any improvements or anything you want ππ