I am relatively new to the Next.js, and for some reason, in my local system I can not access environment variables. I am giving all the related files here.
pages/index.js
import type {NextPage} from 'next'
import {useEffect} from "react";
const Home: NextPage = (props) => {
useEffect(()=>{
console.log("From Client API_URL:", process.env.API_URL)
console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
}, []);
return (
<>
Hello World!
</>
)
}
export async function getServerSideProps() {
console.log("From Client API_URL:", process.env.API_URL)
console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
return {
props: {
hello: "World!"
}
}
}
export default Home
.env.local
file
API_URL:https://fakestoreapi.com/
NEXT_PUBLIC_API_URL:https://fakestoreapi.com/
In the browser, I am getting this in the console.
In the server, I am getting this
> npm run dev
> dev
> next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Loaded env from C:\...\next-app\.env.local
warn - SWC minify beta enabled. https://nextjs.org/docs/messages/swc-minify-enabled
event - compiled client and server successfully in 361 ms (217 modules)
wait - compiling / (client and server)...
event - compiled client and server successfully in 92 ms (220 modules)
From server API_URL: undefined
From server NEXT_PUBLIC_API_URL: undefined
wait - compiling /_error (client and server)...
event - compiled client and server successfully in 78 ms (221 modules)
next js version: 12.0.7
node js version: 14.17.1
npm version: 8.1.4
CodePudding user response:
it seems your .env.local
not properly config ,
you should when assigning value to a key using = not :
.env.local
API_URL=https://fakestoreapi.com/
NEXT_PUBLIC_API_URL=https://fakestoreapi.com/
CodePudding user response:
You cannot access keys in .env files on client side in Next.js which doesnot start with NEXT_PUBLIC_ .
Also, your file should be .env .
.env
NEXT_PUBLIC_API_URL:https://fakestoreapi.com/
pages/index.js
import type {NextPage} from 'next'
import {useEffect} from "react";
const Home: NextPage = (props) => {
useEffect(()=>{
console.log("From Client API_URL:", process.env.NEXT_PUBLIC_API_URL)
console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
}, []);
return (
<>
Hello World!
</>
)
}
export async function getServerSideProps() {
console.log("From Client API_URL:", process.env.NEXT_PUBLIC_API_URL)
console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
return {
props: {
hello: "World!"
}
}
}
export default Home