Reputation: 4653
I'm using NextJS v 10.0.9. I have created an .env.development.local
file in the root of my project, as described in the docs. Contents:
API_SERVER=http://127.0.0.1:5000/map/abc123
In an API route:
pages/api/objects.js
export function getObjects() {
console.log(process.env.API_SERVER)
}
But when I run the application with next dev
, this prints undefined
. I have restarted my server numerous times since defining/changing the variable, but always get undefined
. I've also tried adding a NEXT_PUBLIC_
prefix, which shouldn't be necessary and isn't desired, but I wanted to see what would happen. Result: no change. I've also tried using .env.local
.
What am I doing wrong?
Update: I found this line in the docs on API routes: "For an API route to work, you need to export a function as default (a.k.a request handler), which then receives the following parameters: req, res."
So I've modified the code in my API route to:
export default function getObjects(req, res) {
console.log("test ", process.env.API_SERVER)
}
But it still isn't working. I do not have a next.config.js
file because, as I understand it, this is no longer necessary as of NextJS 9.4.
I have also tried declaring and using an entirely new variable in the file (TEST=value
), but this is also undefined when I try to use it in the API route.
Upvotes: 0
Views: 3188
Reputation: 4653
The issue was how I was calling the API route. When I visited it directly in the browser, the environment variable was available and printed in the console just fine. But I had been following a tutorial that wasn't written for NextJS, and it had me import the API functions directly:
// WRONG WRONG WRONG
import getObjects from './api/objects'
// [...]
export default function MyApp({}) {
useEffect(() => {
getObjects().then(data => {
// do stuff
}
})
}
Upvotes: 2