1

I have a Next.js project. I have created .env file and using enviroments from this file in server.js file. But when I want to reach these enviroments from component, I can't access. What should I do?

This is .env file:

SERVER_PORT=3000
DOMAIN=127.0.0.1
DATABASE=dburl

This is server.js file:

require('dotenv/config')

const port = process.env.SERVER_PORT || 3000
server.listen(port, (err) => {
      if(err) throw err
      console.log(`Server listen on http://127.0.0.1:${port}`)
    })

This is any component of react:

axios
    .get(`http://${process.env.DOMAIN}/api/improve-language`)
    .then(res => {
      ...
    })
    .catch(err =>{
      console.log(err)
    })
yusufcode
  • 391
  • 5
  • 19
  • Does this answer your question? [Nextjs components can't access env.local variables](https://stackoverflow.com/questions/69421139/nextjs-components-cant-access-env-local-variables) – Leau Dec 26 '21 at 00:12
  • Does this answer your question? [NextJS environment variables aren't working](https://stackoverflow.com/questions/63257107/nextjs-environment-variables-arent-working) – juliomalves Dec 26 '21 at 00:29

1 Answers1

2

Based on the documentation if you want to use the env variables in the browser, they must be named with prefix NEXT_PUBLIC_.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Peter Kusza
  • 361
  • 3
  • 11
  • I've changed name of `.env` file to `.env.local` and changed enviroment name from `DOMAIN` to `NEXT_PUBLIC_DOMAIN`. But still not working... – yusufcode Dec 26 '21 at 10:29