0

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.

4
  • I think you have to rename the file to .env.development Commented Mar 28, 2021 at 19:40
  • Thanks for the suggestion. I have tried .env.development, .env.development.local and .env.local. All three get loaded when I run next dev, but none are populating the variable in the API route. Commented Mar 28, 2021 at 20:01
  • Do you have next.config.js file in your project? Commented Mar 28, 2021 at 20:09
  • No, because I'm on 10.0.9, so the docs say I only need to create the appropriate .env file and use process.env.VAR_NAME. Commented Mar 28, 2021 at 20:14

1 Answer 1

2

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
        }
    })
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.